eozzy
eozzy

Reputation: 68650

set default values if empty

I'm changing the text of an element based on the input:

$("input#txtName").keyup(function(){
      $(".website-info h3 strong").text($(this).val());
    });
$("input#txtUrl").keyup(function(){
      $(".website-info h3 small").text($(this).val());
    });

It works, but I want to show default values as soon as the text is empty or user has entered nothing to prevent white space. I tried the if... is.(:empty) condition but it doesn't help cause .text doesn't seem to set default values.

Upvotes: 6

Views: 7108

Answers (3)

Ed Orsi
Ed Orsi

Reputation: 2306

Consider using the placeholder HTML attribute of input elements. Set the attribute in your HTML

<input type="text" id="txtName" placeholder="default text here" />

or with jQuery after the page loads

$("input#txtName").attr("placeholder", "default text here");

Here is the MDN page on the <input> element

Upvotes: 1

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19662

Change both of your text assignments to a variant of the following:

$(".website-info h3 small").text(($(this).val().length) ? $(this).val() : "Your default value here");

Be warned that this will not throw the default value if the user enters a whitespace - if you'd like to do this, you'll need to edit the ternary operator accordingly.

Upvotes: 0

tom
tom

Reputation: 19153

A concise and pretty standard way of doing this is using the || operator.

$("input#txtName").keyup(function(){
      $(".website-info h3 strong").text($(this).val() || "Default text");
    });

Upvotes: 7

Related Questions