Reputation: 155872
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.
Upvotes: 4
Views: 5408
Reputation: 8275
You can check whether the option has an attribute value :
if($('#mySelect option:selected').attr('value')) { ... }
Note :
Strangely, for this case, with some jQuery versions (it works with v1.9.1), .attr('value') !== [0].value
-> the DOM value refers to the text when there is no value, but the attr
function returns undefined
.
Example : jsFiddle
EDIT :
it looks like $('#mySelect option:selected')[0].getAttribute("value")
gives null in almost cases (tested on FF / Chrome / IE8&9). On IE7, it gives an empty string...
Upvotes: 1
Reputation: 13175
Use the option[value]
to select only options
with attribute value
:
var selectedOptionText = $('#mySelect option[value]:selected').text();
http://jsfiddle.net/ouadie/tqVUp/
Upvotes: 2
Reputation: 1374
Why not add a blank value to the default option? Like so:
<option value="">Please Choose</option>
Then you can use this jquery:
if($("select").val() === ''){
alert('no item chosen');
}
Demo: fiddle
Upvotes: 0
Reputation: 12069
I have used this:
$("#mySelect").change(function(){
if(!$("#mySelect option:selected").is('[value]'))
console.log('no value');
});
Working http://jsfiddle.net/5ht7g/
Upvotes: 2