最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Check if input is empty and show status of it - Stack Overflow

programmeradmin6浏览0评论

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>

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>
Share Improve this question edited Jan 15, 2012 at 4:14 PeeHaa 72.8k60 gold badges194 silver badges264 bronze badges asked Jan 12, 2012 at 22:45 Satch3000Satch3000 49.5k90 gold badges225 silver badges349 bronze badges
Add a ment  | 

2 Answers 2

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

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

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');
  }
});
发布评论

评论列表(0)

  1. 暂无评论