-1

I hope there is a shorter way to check if an option inside sela exists.

Any suggestion?

var str = 'white moon';
var x = 0;
$('#sela > option').each(function(){
if($(this).text() == str){x = 1;}
});

if(x == 1){console.log(x);}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id='sela'>
<option>blue sky</option>
<option>gold sun</option>
<option>white moon</option>
</select>
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 2
    Possible duplicate of [Check if an select option exists based on text in jQuery 1.7](https://stackoverflow.com/questions/11639023/check-if-an-select-option-exists-based-on-text-in-jquery-1-7) – Manoz Jan 21 '19 at 13:28
  • @Manoz, the question is duplicated, but the answer is much better here (`Jitendra's` answer); – qadenza Jan 21 '19 at 13:30
  • I still don't see any difference b/w both the accepted answers. This is clearly a duplicate. – Manoz Jan 21 '19 at 13:34
  • @qadenza the two answers are identical (first answer on duplicate and Jitendra's here) - or am I missing something? – freedomn-m Jan 21 '19 at 13:58

3 Answers3

1

This will check given option exist on dropdown.

$(document).ready(function() {
  console.log($("#sela option:contains(white moon)").length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='sela'>
  <option>blue sky</option>
  <option>gold sun</option>
  <option>white moon</option>
</select>
Jitendra G2
  • 1,196
  • 7
  • 14
  • It won't work if you want to check if an option exists (as requested in the question) if the look-for is also part of another option eg `` as `$("select option:contains(blue)")` will find `blue moon` and not `blue`. It's ok if you know that's what you're looking for, but not to *explicitly* **"check if an option exists"**. – freedomn-m Jan 21 '19 at 14:01
  • For an exact match, use the existing answer here: https://stackoverflow.com/a/11639134/2181514 – freedomn-m Jan 21 '19 at 14:03
1
if ($('#sela option').length > 0) {
  console.log('exist');
}

//if specific option exist
if($("#sela option[value='yourValue']").length > 0) {
}
Zeljka
  • 376
  • 1
  • 10
0

Why not giving value attribute to your option ? then you can easily selected the one you want

var str = 'white moon';
console.log($('#sela>option[value="'+str+'"]'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id='sela'>
<option value="blue sky">blue sky</option>
<option value="gold sun">gold sun</option>
<option value="white moon">white moon</option>
</select>
Sylvain Attoumani
  • 1,213
  • 1
  • 15
  • 34