Set defaults if empty

I am changing the text of an element based on 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 the default values ​​as soon as the text is empty or the user has not added anything to prevent a space. I tried the condition if... is.(:empty) , but this does not help to call .text , it does not seem to set default values.

+4
source share
3 answers

A concise and fairly standard way to do this is to use the || .

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

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

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

or with jQuery after loading the page

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

Here is the MDN page in the <input> element

+1
source

Change both of your text assignments to one of the options:

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

We will warn that this will not cause the default value if the user enters a space - if you want to do this, you need to edit the ternary operator accordingly.

0
source

All Articles