shorter way to check if an option exists

17
January 21, 2019, at 11:20 PM

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>

Answer 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>

Answer 2
if ($('#sela option').length > 0) {
  console.log('exist');
}
//if specific option exist
if($("#sela option[value='yourValue']").length > 0) {
}
Answer 3

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>

READ ALSO
Looking for javascript library to save and restore html form, including restore from php&#39;s $_POST

Looking for javascript library to save and restore html form, including restore from php's $_POST

I am looking for a library to restore html form fields (inputs, selects, checkboxes and everything else) state using javascriptState of the form should be previously saved in php's $_POST data or other serialized format

46
async/await with event-stream mapSync not working

async/await with event-stream mapSync not working

The await commands that I have commented with //******This await does not work */ do not seem to workNot sure if this is something related to the fact they are in an event stream or a problem with the promise in the imported module

54
How can I refresh the paypal-rest-sdk OAuth2 token?

How can I refresh the paypal-rest-sdk OAuth2 token?

I'm trying to get confirmation as to whether the paypal rest sdk handles token refresh automatically or if I need to do it manually

15
Why isn&#39;t my delete button working properly? [on hold]

Why isn't my delete button working properly? [on hold]

I'm trying to fix the delete function of my Single Page Application, its not working how its suppose toI don't know where the problem lies if its the javascript, php or html

20