Tuesday, March 26, 2013

Make the CheckBox a Required Field using jQuery




HTML:

<div class="smallDiv">
<h2>Check Atleast One CheckBox before submitting the Form</h2>
<asp:CheckBox ID="cb1" runat="server" Text="Option One" /><br />
<asp:CheckBox ID="cb2" runat="server" Text="Option Two" /><br />
<asp:CheckBox ID="cb3" runat="server" Text="Option Three" />
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
ToolTip="Select atleast one checkbox before clicking" />
<br /><br />
Tip: If the user has checked atleast one checkbox, and clicks the
Submit button, a postback occurs, otherwise the user is prevented
from submitting the form.
</div>

Jquery Script:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function () {
$('input[id$=btnSubmit]').click(function () {
var checked = $(':CheckBox:checked').length;
if (checked == 0) {
alert('Atleast one checkbox should be selected!');
e.preventDefault();
}
else {
alert('postback occured!');
}
});
});
</script>

No comments:
Write comments
Recommended Posts × +