Best way (with jQuery) to check that an empty <option> is not selected
html-select, javascript, jquery
Solution
I have used this:
$("#mySelect").change(function(){
if(!$("#mySelect option:selected").is('[value]'))
console.log('no value');
});
Working http://jsfiddle.net/5ht7g/
Problem
I'm using ASP.Net's drop-down helpers, and they produce HTML like this: ``` <select id="mySelect" name="mySelect"> <option>Please Choose</option> <option value="1">Name A</option> <option value="2">Name B</option> <option value="3">Name B</option> </select> ``` I want to validate that this `<select>` is not set to the Please Choose `<option>` in lots of places. Often the text is something other than Please Choose, but the `<option value>` attribute is always skipped for the default option. The problem is that if you request the `value` and it is not set you get the `option`'s text: ``` // Gets value as 'Please Choose' var value = $('#mySelect').val(); // Also gets the value as 'Please Choose' var value = $('#mySelect option:selected').attr('value'); ``` I want a check that returns true only if the `<option value>` attribute is actually populated. My best solution to this so far is: ``` // Check that the value and text of an option are different var value = $('#mySelect').val(); var selectedOptionText = $('#mySelect option:selected').text(); var check = value != selectedOptionText; ``` This doesn't seem very reliable though - if we get an option like `<option value="1">1</option>` it will never appear to be valid. Is there any way to check that the `<option value>` attribute is empty? I'm using jQuery here but a pure Javascript solution would be good too.