Satch3000
Satch3000

Reputation: 49384

JQuery Check if input is empty and show status of it

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>

Upvotes: 1

Views: 4878

Answers (2)

Blender
Blender

Reputation: 298206

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');
  }
});

Upvotes: 2

elijah
elijah

Reputation: 2924

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

input.change( function() {
  var empty = ( input.val() == '' );
  status
    .toggleClass('ok', !empty)
    .toggleClass('noTxt', empty);
});

Upvotes: 5

Related Questions