Check / uncheck by entering radio using javascript

I have a radio input group. If the radio is checked, and I press it again, it will be removed.

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

 <input name="options" type="radio" onClick="resetMeIfChecked()"> <input name="options" type="radio" onClick="resetMeIfChecked()"> <input name="options" type="radio" onClick="resetMeIfChecked()"> 
+7
source share
10 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 does not mean that the radio buttons are intended for use. I think that it will be better for you with the checkbox selected, where you can clear all the checkboxes except the current click (therefore, a maximum of 1 is always selected)

Working example

+6
source

try the following:

 function resetMeIfChecked(radio){ if(radio.checked && radio.value == window.lastrv){ $(radio).removeAttr('checked'); window.lastrv = 0; } else window.lastrv = radio.value; } <input value="1" name="options" checked="checked" type="radio" onClick="resetMeIfChecked(this)" />A <input value="2" name="options" type="radio" onClick="resetMeIfChecked(this)" />B <input value="3" name="options" type="radio" onClick="resetMeIfChecked(this)" />C 
+2
source

It is pretty simple. Just follow a simple example and

 var rdblength=document.formname.elementname.length; alert('length='+rdblength); for(i=0;i<rdblength;i++){ document.formname.elementname[i].checked=false; } 

Just find the length and make each checked index = true / false.

Ping me at: - http://manojbardhan2009.blogspot.com

+2
source

I had the same problem and understood this. None of the answers above work exactly the way I wanted - most of them require an additional button to reset the radio. The goal was to turn off the radio by clicking on the radio itself.

Here's the fiddle: http://jsfiddle.net/MEk5Q/1/

The problem was very complicated, because the value of the switch changes before the click event fires, so when we listen to the event, we cannot determine whether the switch was already set or not. In both cases, it has already been verified. Another approach was to listen to the mousedown event. Unlike click , it starts before changing the radio checked attribute, but deleting it inside the event handler does not give us anything, since it is checked again during the mouseup event.

My answer is a bit ugly workaround, so I usually don’t offer it to others, and I probably will refuse it myself. It works , but it includes a 20 ms timeout function, which I do not like in such cases.

Here is the code explanation:

 $('input[type="radio"]').on('mousedown', function() { if (this.checked) { //on mousedown we can easily determine if the radio is already checked this.dataset.check = '1'; //if so, we set a custom attribute (in DOM it would be data-check="1") } }).on('mouseup', function() { if (this.dataset.check) { //then on mouseup we determine if the radio was just meant to be unchecked var radio = this; setTimeout(function() {radio.checked = false;}, 20); //we give it a 20ms delay because radio checking fires right after mouseup event delete this.dataset.check; //get rid of our custom attribute } }); 

As a timeout function, I could use a string (less record), but as far as I know, it will be eval 'ed. Although I do not trust the eval function, I prefer the anonymous function.

One more thing - one may ask, why is spreading the code to two separate event handlers, while we can run the timeout function on mousedown? Well, what if someone clicks the mouse on the radio and holds it for a few seconds or even someone is just a very slow person;). Typically, with this solution, we omit the lag problem between mousedown and mouseup .

If you need more information about dataset , here is the MDN link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset This property comes with HTML5 and may not be cross-server, therefore, if you want 100% compatibility, replace it with any other solution that will contain data, you name it.

Sorry for jQuery here and there, but I hope everything is fine with it - it was a lot easier.

I hope you will like it.

+2
source

 $('input[type="radio"]').on("mousedown", function () { if (this.checked) { $(this).one("click", function () { this.checked = false; }); } }); 
+2
source

This behavior is not expected for switches, and I do not recommend it at all. Try to find another way to achieve this. Use another widget or other parameter to reset the field value:

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

+1
source

I was never too happy that I was forced to take aim at this tiny radio button, so I came up with a larger goal and a way to turn off the radio group without resorting to anything that would upset the HTML / JavaScript purists.

This method is based on the fact that it did not pester radio buttons with the help of event handlers, but instead checked only the proxy server for reading. Everything is contained in what is below in pure JavaScript, using the radio group to select the type of cheese or not cheese at all.

I intentionally did not use the style in this example to avoid this added layer. The Dump button tells you what the three checked states are, so use it to poll what happened after hitting the radio or text input elements. For example, for simplicity, I used global storing of the former state, but a more elegant method is to use the data set that I use in the real code of my application.

 <!DOCTYPE html> <html> <head> <title>Uncheck a radio button</title> <script> function attachEventListener(target, eventType, functionRef, capture) { "use strict"; if (typeof target.addEventListener !== 'undefined') { // Most modern browsers target.addEventListener(eventType, functionRef, capture); } else if (typeof target.attachEvent !== 'undefined') { // IE target.attachEvent('on' + eventType, functionRef); } else { eventType = 'on' + eventType; if (typeof target[eventType] === 'function') { var oldListener = target[eventType]; target[eventType] = function() { oldListener(); return functionRef(); }; } else { target[eventType] = functionRef; } } } </script> </head> <body> <form> <input id="Cheddar-radio" class="radio" type="radio" name="Cheeses-0" value="Cheddar Cheese" tabindex="-1"></input> <input id="Cheddar-text" type="text" readonly value="Cheddar Cheese" tabindex="-1"></input><br> <input id="Swiss-radio" class="radio" type="radio" name="Cheeses-0" value="Swiss Cheese" tabindex="-1"></input> <input id="Swiss-text" type="text" readonly value="Swiss Cheese" tabindex="-1"></input><br> <input id="American-radio" class="radio" type="radio" name="Cheeses-0" value="American Cheese" tabindex="-1"></input> <input id="American-text" type="text" readonly value="American Cheese" tabindex="-1"></input><br><br> <input onclick="dumpStates()" type="button" name="button" value="dump" tabindex="-1"></input> </form> <script> window.onload = addRadioListeners; function addRadioListeners() { // But do it on the -text elements. attachEventListener(document.getElementById('Cheddar-text') , 'mousedown', rememberCurrentState, false); attachEventListener(document.getElementById('Swiss-text') , 'mousedown', rememberCurrentState, false); attachEventListener(document.getElementById('American-text'), 'mousedown', rememberCurrentState, false); attachEventListener(document.getElementById('Cheddar-text') , 'mouseup', checkNewState, false); attachEventListener(document.getElementById('Swiss-text') , 'mouseup', checkNewState, false); attachEventListener(document.getElementById('American-text'), 'mouseup', checkNewState, false); } function dumpStates() { console.log(document.getElementById('Cheddar-radio').checked + ' ' + document.getElementById('Swiss-radio').checked + ' ' + document.getElementById('American-radio').checked); } var elementWasChecked; // Global - Could just as well use a dataset attribute // on either the -radio or -text element and check it instead. function rememberCurrentState(event) { var element; var radioElement; element = event.target; radioElement = document.getElementById(element.id.replace(/text/,'radio')); elementWasChecked = radioElement.checked; radioElement.checked = true; } function checkNewState(event) { var element; var radioElement; element = event.target; radioElement = document.getElementById(element.id.replace(/text/,'radio')); var currentState = radioElement.checked; if (elementWasChecked === true && currentState === true) { console.log('Changing ' + radioElement.id + ' to false.'); radioElement.checked = false; } }; </script> </body> </html> 

If you click on the switches, they will work properly. If you click on text items next to them, they are a proxy for switches with one exception. If you click on a text element that has an associated radio button that has already been verified, it will remove it. Therefore, a text proxy server is triggered by an event, not by switches.

An added benefit is that now you can also click on the larger target of the text.

+1
source

I am using this. You just save the value of the pre-click and! it matters.

 <input type=radio name="myoptions" value="1" onmousedown="this.tag = this.checked;" onclick="this.checked = !this.tag;"> 
+1
source

If you want to make it simple and not averse to using the double-click event, try something like this:

 <input name="options" type="radio" ondblclick="this.checked=false;"> 
0
source

@Jerjer's answer is almost perfect, but radio stations can also switch using arrows if the radio group has focus (therefore, mousedown events are not enough). Alas, the radio group is also checked when activated by a focus shift ( Tab ), which may undesirably check one option. Therefore, space should uncheck the focused radio, just like the behavior of the flag.

This code fixes this for all radio stations (most of the credit still goes to jerjer):

 window.addEventListener("DOMContentLoaded", function() { var radios = document.querySelectorAll("input[type=radio]"); for(var i=0; i<radios.length; ++i) { radios[i].addEventListener("click", function(e) { if(e.target.checked && e.target.value == window.lastrv){ e.target.checked = false; window.lastrv = 0; } else window.lastrv = e.target.value; }); radios[i].addEventListener("keypress", function(e) { if(e.keyCode==32) e.target.click(); }); } }); 
0
source

All Articles