1

I have an input which I need to check whether it is empty or not:

<input id="myinput" name="myinput" type="text" value="hello" />

The input above could change any time, so I need to check it on onchange?

If my input is not empty then I need to add the class ok or else add class noTxt.

The class could be added to the element below.

<div id="status" style="display:none;">&nbsp;</div>

2 Answers 2

5
var input = $('#myinput');
var status = $('#status');

input.change( function() {
  var empty = ( input.val() == '' );
  status
    .toggleClass('ok', !empty)
    .toggleClass('noTxt', empty);
});
Sign up to request clarification or add additional context in comments.

Comments

2

This might work:

$('#myinput').on('keyup keydown keypress change paste', function() {
  if ($(this).val() == '') {
    $('#status').removeClass('okay').addClass('not-okay');
  } else {
    $('#status').addClass('okay').removeClass('not-okay');
  }
});

1 Comment

this will switch the class on #myinput, not #status

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.