Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

Search strings with "indexOf" fails

$
0
0

I'd like to display the message Exist! if the strings in the input field includes strings within the li tags.

When I input cccc, the Exist! message appears successfully. However when I input aaaa or bbbb it fails and displays Nop!. I'm wondering why. I hope someone help me.

$('input').on('input', function() {
  var keyword = $(this).val();
  var targetText;
  var msg = $('#msg');
  if (keyword != '') {
    $('ul li').each(function() {
      targetText = $(this).text();
      if (targetText.indexOf(keyword) != -1) {
        msg.text('Exist!');
      } else {
        msg.text('Nop!');
      }
    });
  } else {
    msg.text('');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="text"><div id="msg"></div><ul><li>aaaaaa</li><li>bbbbbbbb</li><li>cccccccccc</li></ul>

Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>