Reputation: 75
I use this code to check if dropdown opton is selected before submit. On my page I have 3 dropdown menus, but only the first works correctly.
Is there a way to extend function for the 2nd and 3rd dropdowns?
My script:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var year = $('#year option:selected').val();
if(year == "")
{
$("#msg").html("Please select a year");
return false;
}
});
});
</script>
My HTML:
<div id="msg"></div>
<form method="post" action="">
<select id="year">
<option value="">OLLA</option>
<option>1991 </option>
<option>1992 </option>
<option>1993 </option>
<option>1994 </option>
<option>1995 </option>
</select>
<div id="msg"></div>
<form method="post" action="">
<select id="year">
<option value="">OLLA</option>
<option>1991 </option>
<option>1992 </option>
<option>1993 </option>
<option>1994 </option>
<option>1995 </option>
</select>
<input type="submit" name="submit" id="submit">
</form>
Upvotes: 1
Views: 2914
Reputation:
You could, of course, set an action on the DDL to ensure that a value has been set (enabling the submit button afterwards) thus putting the emphasis of validation directly on the control itself, rather than the submit button. (Just another way of skinning the same cat!)
Upvotes: 0
Reputation: 147413
If you put the listener on the form, it will be this
within the function so you can just do something like:
$("<form selector>").click(function(){
if (this.year.value == "") {
$("#msg").html("Please select a year");
return false;
} else {
$("#msg").html("");
}
})
You could also check whether the selected index is greater than zero. If it's zero or -1, then either the first or no option is selected (respsectively).
You should turn the ID attributes into NAME attributes, then you can repeat them (and they will be successful when the form is submitted).
Oh, and never name a form control "submit" as it will shadow the form's submit method, making it impossible to call it.
Upvotes: 0
Reputation: 68596
ID's should be unique and only used once. I advise you to give them all the class msg
instead, e.g.
<div class="msg"></div>
...
<div class="msg"></div>
Also, give your selects a class too instead, for the same reason, both:
<select class="year">
Your jQuery would also be changed to:
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(){
var year = $('.year option:selected').val();
if(year == "") {
$(".msg").html("Please select a year");
return false;
}
});
});
</script>
Upvotes: 2
Reputation: 1455
Because Ids of both element are same so selector works with first id match this case .Try to use different ids or USe Class Instead of ID or use the jquery each function http://api.jquery.com/each/
Upvotes: 0