t4d_ t4d_ - 4 months ago 25
jQuery Question

(select > option) exact text issue using input value and :contains method in jquery

Introduction: My code consists of just two elements. First element is input

(#nameInput)
and second is select
(#select)
.

My goal is to check if there is with text equal to current
#nameInput
value.

Please, take a look on example below, if inserted text in input already exists in
option
the border of input turns red (addClass error).

But, there is a issue with
:contains
, because it search for text included in option text instead exact match I looking for.

As shown on example below, there are options with text
a
&
aaa
, but the error(class) appears even if
aa
or
aaaa
are inserted.

One more example, which doesn't work ->
my option
- error appears when only
my
is inserted.



$("#nameInput").change(function(){
var t = $(this);
var t_val = $(this).val();

if(
$("#select option:contains(" + t_val + ")" ).length
) {
t.addClass("error");
}
else {t.removeClass("error");}

});

input, select {width: 50%; height: 32px;}
input.error {border: 5px solid red;}

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<input id="nameInput" type="text"/><br/><br/>
<select id="select">
<option value="default" selected disabled>Select..</option>
<option class="option">a</option>
<option class="option">aaa</option>
<option class="option">bbb</option>
<option class="option">bbbbbb</option>
<option class="option">my option</option>
</select>




Answer

Use input event, .filter() to check if .textContent of input is equal to a #select option element

$("#nameInput").on("input", function() {
  var t = $(this);
  var t_val = t.val();

  if (
    $("#select option").filter(function() {
      return this.textContent === t_val
    }).length
  ) {
    t.addClass("error");
  } else {
    t.removeClass("error");
  }

});
input,
select {
  width: 50%;
  height: 32px;
}
input.error {
  border: 5px solid red;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<input id="nameInput" type="text" />
<br/>
<br/>
<select id="select">
  <option value="default" selected disabled>Select..</option>
  <option class="option">a</option>
  <option class="option">aaa</option>
  <option class="option">bbb</option>
  <option class="option">bbbbbb</option>
  <option class="option">my option</option>
</select>