Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  189] [ 7]  / answers: 1 / hits: 29066  / 12 Years ago, wed, march 21, 2012, 12:00:00

Is it possible to detect if no option was explicitly selected in a select box?



I have tried these methods but none of them works:



<select id=mySelect>
<option value=1>First</option>
<option value=2>Second</option>
<option value=3>Third</option>
<option value=4>Fourth</option>
</select>


Trial 1:



alert($('#select option:selected').length); // returns 1


Trial 2:



alert($('#select option[selected=selected]').length); // returns 1


Trial 3:



alert($('#select option:selected').attr('selected')); // returns 'selected'


Any ideas SO people?


More From » jquery

 Answers
19

Try This:



<select id=mySelect>
<option value=1>First</option>
<option value=2>Second</option>
<option value=3>Third</option>
<option value=4>Fourth</option>
</select><input type=button id=btncheck value=check/>


Use this JS:



$('#btncheck').click(function(){
if ($(#mySelect )[0].selectedIndex <= 0) {
alert(Not selected);
}
else
alert(Selected);
});


​It will check if your dropdown was selected.



Try this fiddle: http://jsfiddle.net/aPYyt/



​Hope it helps!



PS: You will have to make first value as default value.


[#86702] Tuesday, March 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;