JQuery | Check/uncheck the radio button on click using jquery

|
| By Webner

When we click radio button, it gets checked. Once it gets checked it doesn’t get unchecked when again clicked. We can use checkbox for checked/unchecked status of input, but sometimes requirement arises when we need to use radio button for checked/unchecked status instead of checkbox.

Solution:

Suppose following is the HTML for the problem:

<form>
<input type="radio" name="enableSettings1" id="enableSettings1" class="radioSettings">
<label for="enableSettings1">Enable Settings 1<label>
<br/>
<input type="radio" name="enableSettings2" id="enableSettings2" class="radioSettings" checked/>
<label for="enableSettings2">Enable Settings 2</label%gt;
<form>

In the above HTML, the second radio button is already checked. If we want to make it unchecked, we won’t be able to get it unchecked. To solve this problem, we can use following jquery script:

<script>
var radioArray = new Array(2);
$('.radioSettings').each(function()
{
if($(this).prop('checked') == true)
{
radioArray[$(this).attr('id')] = 1;
}
else
{
radioArray[$(this).attr('id')] = 0;
}
});
$('.radioSettings').click(function(){
radioId = $(this).attr('id');
if(radioArray[radioId] == 1)
{
$(this).prop('checked', false);
radioArray[radioId] = 0; // changing the value of given key of array
}
else
{
$(this).prop('checked', true);
radioArray[radioId] = 1; // changing the value of given key of array
}
});
</script>

In the jquery script, initially, variable radioArray has been declared as array to store checked/unchecked status of radio buttons on page load. On page load, array will be in key value form, where key will be id of radio button and value will 1 for checked and 0 for unchecked status.

So array will be in the form:

radioArray[‘enableSettings1’] = 0;
radioArray[‘enableSettings2’] = 1;

Now, on click event of radio buttons, radio buttons get checked if radio buttons are in unchecked status and get unchecked if radio buttons are on unchecked status. Along with checked/unchecked property of radio buttons, we are changing the values of array. If we don’t update the array values, the checked/unchecked property will not change after first click of radio buttons. To change checked/unchecked status everytime on click of radio buttons, we will update the status of radio buttons. We are maintaining the previous values of checked/unchecked status of radio buttons before every click event.
Now, we are able to check/uncheck the radio buttons any number of times on click event.

Leave a Reply

Your email address will not be published. Required fields are marked *