Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check/uncheck radio input with javascript

I have a radio input group. If a radio is checked and I click again it becomes unchecked.

Is there a way to get the previous status of the radio onClick event?

<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
like image 851
NoOneElse Avatar asked Jun 06 '11 12:06

NoOneElse


People also ask

How do I uncheck a radio in JavaScript?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true . When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked.

How do I check uncheck a checkbox input or radio button?

$( "#x" ). prop( "checked", false );


2 Answers

jQuery edition

// bind to retrieve old status
$('input[type="radio"]').mousedown(function() { 
    // if it was checked before
    if(this.checked) {
        // bind event to reset state after click is completed
        $(this).mouseup(function() {  
            // bind param, because "this" will point somewhere else in setTimeout
            var radio = this;
            // apparently if you do it immediatelly, it will be overriden, hence wait a tiny bit
            setTimeout(function() { 
                radio.checked = false; 
            }, 5); 
            // don't handle mouseup anymore unless bound again
            $(this).unbind('mouseup');
        });
    }
});

But again, this is not how radio buttons are intended to be used. I think you'd be better of with a set checkbox'es where you could uncheck all other checkboxes than the current clicked (hence always max 1 selected)

A working example

like image 181
mkilmanas Avatar answered Sep 27 '22 21:09

mkilmanas


This behavior is not the expected one for radio buttons and I don't recommend it at all. Try to find another way of achieving this. Use another widget or another option to reset the field value:

http://jsfiddle.net/marcosfromero/rRTE8/

like image 28
marcosfromero Avatar answered Sep 27 '22 22:09

marcosfromero