Cover Image for jQuery radio button
81 views

jQuery radio button

The radio buttons are a type of input element that allow users to select one option from a group of choices. To work with radio buttons using jQuery, you can access and manipulate their properties and states.

Here’s an example of creating and working with radio buttons using jQuery:

HTML:

<label>
  <input type="radio" name="gender" value="male"> Male
</label>
<label>
  <input type="radio" name="gender" value="female"> Female
</label>
<label>
  <input type="radio" name="gender" value="other"> Other
</label>
<button id="submitBtn">Submit</button>

JavaScript/jQuery:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
  // Event handler for the submit button
  $('#submitBtn').on('click', function() {
    // Get the selected radio button value
    var selectedValue = $('input[name="gender"]:checked').val();

    // Display the selected value
    alert('Selected Gender: ' + selectedValue);
  });
});
</script>

In this example, we have three radio buttons with the same name attribute, which groups them together as a single choice set. When a user selects one radio button, the others will automatically be deselected. The jQuery code attaches a click event to the “Submit” button, and when clicked, it retrieves the value of the selected radio button using the :checked selector.

In this case, we use the :checked selector along with the val() method to get the value of the selected radio button. The name attribute is used to group the radio buttons, and the value attribute represents the value of each radio button option.

With this code, when a user selects a radio button and clicks the “Submit” button, an alert will display the selected gender based on the radio button value.

You can use this concept to work with radio buttons in various scenarios, such as form submissions, filtering data, or handling user preferences.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS