Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.

Here is my html code ..

<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />

<br />

<input type="radio" name="B"  onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />

Here is the javascript code

function check() {
    //logic to check for duplicate selection
    alert('Its already selected');
    return false;
}

And here is the demo The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.

NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.

like image 800
iJade Avatar asked Mar 18 '14 09:03

iJade


1 Answers

In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.

try this code,

html

<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />

JS

var counterA = 0;
var counterB = 0;
$(document).ready(function () {
    if ($("input:radio[name=A]").is(":checked") == true) counterA++;
    if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});

$('input:radio[name=A]').click(function () {
    if (counterA == 1) {
        alert('already checked');
        return false;
    } else {
        counterA++;
    }
});
$('input:radio[name=B]').click(function () {
    if (counterB == 1) {
        alert('already checked');
        return false;
    } else {
        counterB++;
    }
});

SEE THIS DEMO

like image 87
CJ Ramki Avatar answered Sep 27 '22 21:09

CJ Ramki