javascript radio

Javascript Radio

If you're a web developer, you're probably familiar with radio buttons. Radio buttons are a type of form element that allow users to select only one option from a list of options. In this blog post, I'll be discussing how to use JavaScript to manipulate radio buttons and make them more user-friendly.

Basic Radio Button

Here is an example of a basic radio button HTML code:

<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female

The above code will display two radio buttons, one for male and one for female. The 'name' attribute is used to group the radio buttons together so that only one can be selected. The 'value' attribute is the value submitted to the server when the form is submitted. When a user selects a radio button, the 'value' attribute of the selected radio button is sent as part of the form data.

JavaScript Manipulation

Now let's see how we can use JavaScript to manipulate radio buttons.

Checking and Unchecking Radio Buttons

If you want to check or uncheck a radio button using JavaScript, you can use the 'checked' property:

var maleRadio = document.querySelector('input[value="male"]');
maleRadio.checked = true;

The above code will check the male radio button.

Getting the Selected Radio Button

You can get the selected radio button using the 'checked' property:

var genderRadios = document.getElementsByName('gender');
var selectedGender;
for (var i = 0; i < genderRadios.length; i++) {
  if (genderRadios[i].checked) {
    selectedGender = genderRadios[i].value;
    break;
  }
}

The above code will loop through all the radio buttons with the name 'gender' and check which one is selected. The value of the selected radio button is then stored in the 'selectedGender' variable.

Disabling and Enabling Radio Buttons

You can disable or enable a radio button using the 'disabled' property:

var maleRadio = document.querySelector('input[value="male"]');
maleRadio.disabled = true;

The above code will disable the male radio button.

Conclusion

Javascript can be used to create responsive and interactive forms by manipulating the form elements. Radio buttons are an important element of forms, allowing users to select from multiple options, and JavaScript can be used to make them more user-friendly.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe