userlkjsflkdsvm userlkjsflkdsvm - 6 months ago 26
Javascript Question

Matching input value with text inside span

I am able to match the input value with the span; however, I am only to retrieve the first span in the list I am comparing to. I need to compare to both list items. If the input is equal to either list item then it should be true. I am only getting a match for the first value.

HTML

<input id="search" type="text" class="input">
<ul> <li id="111" class="active" style="display: list-item;"><a href="" onclick="return false;"><span style="display:none">111</span><span style="display: inline;">1-1-1</span></a></li>
<li id="222" style="display: list-item;"><a href="" onclick="return false;"><span style="display:none">222</span><span style="display: inline;">2-2-2</span></a></li>
</ul>


JS

$('#search').on('input',function(){

if( $('#search').val() != $('ul li a span:eq(0)').text()){
return console.log('false')
}
else if( $('#search').val() == $('ul li a span:eq(0)').text()) { return console.log ('true') }

});


jsfiddle

Answer Source

I think that when you call .text() on a list of elements it will return the text of the first element. So you need to iterate through the spans you are interested in and check each one.

Here is an example:

$('#search').on('input',function(){
  var found = false;
  $('ul li a span:first-child').each(function (i, el){
    if ($(el).text() == $('#search').val()) {
      found = true;
      return;
    }
  })
  console.log(found);
});