Reputation: 68650
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
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
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
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