1

Is there any way to assign class by using javascript when there is some values in input field (text field)

-- detailed --

Actually im using background watermark in the input field. So when someone click & type it on the input field then i will clear the background watermark image by css (using :focus selector).

In that way if he move to the next field then still the background watermark showing with the typed text (because onfocus is lift to the next field).

Anyone please?

If so i will make style to clear background watermark image using the class!

2 Answers 2

3
if($.trim($('input[type=text]').val()).length) {
  $(some_target).addClass('new_class');
}

.trim()

.val()

Complete code should look like following:

$('input[type=text]').on('keyup', function() {
  var targetInput = this; // keeping reference of input
  if($.trim(this.value).length) {
    // code for remove watermark
    $(targetInput).addClass('class_for_watermark');
  } else {
    // code for add watermark
    $(targetInput).removeClass('class_for_watermark');
  }
});

And you don't need to :focus css.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, there is also .toggleClass which could simplify the if/else.
0

You mean this?

if ( $input.val() ) {
  // Has a value, do something
  $element.addClass('myClass');
}

1 Comment

Resolving the boolean state of an input's value could return false if the input is 0 or a string containing "0", "false", "null" or any other javascript value that is equal to false.

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.