6

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.

1
  • $(this).val().length Commented Mar 27, 2013 at 21:13

3 Answers 3

7

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");
    });
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.