Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set default values if empty

Tags:

jquery

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.

like image 308
eozzy Avatar asked Mar 27 '13 21:03

eozzy


2 Answers

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");
    });
like image 56
tom Avatar answered Oct 29 '22 20:10

tom


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

like image 21
Ed Orsi Avatar answered Oct 29 '22 22:10

Ed Orsi