I have one dropdown in html and i want to validate it using jquery.
Please select your rating * :
<select id="myDropdown">
<option value="">-Please Select-</optio开发者_JAVA技巧n>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
My Jquery code is like
if ($('#myDropdown option:selected').length == 0)
{
alert("Please select anyone");
}
What I need is if any value is not selected and it remains like -Please Select- and if the user press submit button, then an alert or any appropriate message needs to be displayed Please help
mydropdown = $('#myDropdown');
if (mydropdown.length == 0 || $(mydropdown).val() == "")
{
alert("Please select anyone");
}
See Note below. Also, you don't need the option:selected
(as per Sly's original answer).
On this fiddle, try selecting another value, then try to select the -Please Select-
option. You will see the alert()
.
http://jsfiddle.net/userdude/aS2AM/
EDIT
NOTE: The length test is doing nothing, since it will always report 1, as at least one option is always selected (and your selector is always selecting at least one option, unless the select has no options). I have removed that in this update to the fiddle and code below:
http://jsfiddle.net/userdude/LdN6c/3/
You're not capturing the form submit event.
$(document).ready(function() {
$('#myForm').submit(function(e){ // <<< This selector needs to point to your form.
if ($('#myDropdown').val() == "") {
alert("Please select anyone");
e.preventDefault();
return false;
}
});
});
Note the #myForm
needs to select your actual form element that contains the selected element.
See in action here: http://jsfiddle.net/userdude/LdN6c/1/
jQuery(function($) {
$('#myForm').submit(function(e) {
if ($('#myDropdown').val() == '') {
e.preventDefault();
alert("Please select anyone");
}
});
});
- Edited with form submit event handler
精彩评论