Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 'some text' in a list and if this matches then I am showing select options in .input-1 dropdown, but what I cannot get to work is the opposite where it does not match the string. In this case, I want to hide the select options.

The first part of the code works, but second else if fails

jQuery(document).ready( function() {
$('.input-1 option').each(function() {
var ourOption = $(this).text().toLowerCase(); // convert text to Lowercase
var str = "Some Text";
var res = str.toLowerCase();
if (ourOption.match(res)) {
$(this).css('display', 'block');
}
else if (!ourOption.match(res)) {
$(this).css('display', 'none');
}   
})
});

The current result is that all options are hidden regardless of the matched text so I'm guessing there is an error in my else if or the syntax for no match is incorrect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

.match() is to find a match in string, not compare and return true/false. You need comparison == here:

jQuery(document).ready( function() {
 $('.input-1 option').each(function() {
  var ourOption = $(this).text().toLowerCase(); // convert text to Lowercase
  var str = "Some Text";
  var res = str.toLowerCase();
  if (ourOption.indexOf(res) > -1) {
    $(this).css('display', 'block');
  }
  else {
    $(this).css('display', 'none');
  }   
 })
});

As a matter of fact you do not even need an else-if here, just else is enough... because there are only 2 possibilities true and false and both are covered with if/else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...