Here Laxmikant has explained with an example Validate RadioButtons using jQuery.
When we will be clicked the Submit Button, it will be validated that one Radio Button is checked from the Group of RadioButtons using jQuery.
In this article we will learn with an example, how to Validate RadioButtons using jQuery.
When we are clicked the Submit Button, it will be validated that one Radio Button is checked from the Group of RadioButtons using jQuery.
HTML
The Html code consist of input type radio button and one input type html button.
Note:
Radio buttons are generally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time.
The radio group must have share the same name (the value of the name attribute) to be treated as a group.
Note:The value attribute here defines the unique value which are associated with each radio button.
<body>
<p>Please select your Hobbies:</p>
<input type="radio" name="Hobbies" value="Swimming">
<label for="swimming">Swimming</label><br>
<input type="radio" name="Hobbies" value="Watching Movies" />
<label for="movies">Watching Movies</label><br>
<input type="radio" name="Hobbies" value="Reading" />
<label for="reading">Reading</label><br>
<input type="radio" name="Hobbies" value="Cricket" />
<label for="cricket">Cricket</label><br>
<br />
<input type="button" id="btnSubmit" value="Submit" />
</body>
jQuery Code for Validate RadioButtons using jQuery.
When user clicked at Submit Button, a check is performed whether one RadioButton is checked or not. If RadioButtons length is zero then will be show error alert message.
Otherwise If one RadioButtons is checked, then the validation is successful.
We can use :checked selector and the length property.
The :checked selector works for checkboxes, radio buttons, and options of select elements.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
if ($('input[type=radio][name=Hobbies]:checked').length == 0) {
///Display alert message if no RadioButton is checked.
alert("Please Select your hobbies");
}
else {
var hobbies = $('input[type=radio][name=Hobbies]:checked').val()
//Display alert message if RadioButton is checked.
alert(" Your hobbies is: " + hobbies);
}
});
});
</script>