I have a series of select boxes all with a class value = "topic". I want to submit the form only if one or more boxes have a selected value. My code detects if any of the select boxes have a selected value or not but the form submits either way. Just wondering how to stop the form from submitting?
<select name="Topic_ACH" id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<select name="Topic_Bankruptcy" id="ddlTopic_Bankruptcy" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
etc.
//At least one Topic checkbox must be checked to submit the form
$('#MainContent_btnUpdateSample').click(function (e) {
var anySelected = false;
$(".topic option:selected").each(function () {
if (!$(this).val() == "") {
anySelected = true;
}
});
if (!anySelected) {
alert("You must select at least one topic");
e.preventDefault();
return false;
}
});
2
Answers
You probably should use the
submit
event on the form element instead of theclick
event on the form button. Try out the following:In combination, you might find merit in the
required
attribute for your<select>
elements since that simplifies your logic greatly (adding this element requires the user to select a value; if nothing is selected the browser will automatically display any error messages).(Also you don’t need jQuery)
You can have something like this,