How to detect radio button deselect event? - javascript
Is there an easy way to attach a "deselect" event on a radio button? It seems that the change event only fires when the button is selected.
HTML
<input type="radio" id="one" name="a" />
<input type="radio" id="two" name="a" />
JavaScript
$('#one').change(function() {
if(this.checked) {
// do something when selected
} else { // THIS WILL NEVER HAPPEN
// do something when deselected
}
});
jsFiddle
Why don't you simply create a custom event like, lets say, deselect and let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way.
HTML
<!-- First group of radio buttons -->
<label for="btn_red">Red:</label><input id="btn_red" type="radio" name="radio_btn" />
<label for="btn_blue">Blue:</label><input id="btn_blue" type="radio" name="radio_btn" />
<label for="btn_yellow">Yellow:</label><input id="btn_yellow" type="radio" name="radio_btn" />
<label for="btn_pink">Pink:</label><input id="btn_pink" type="radio" name="radio_btn" />
<hr />
<!-- Second group of radio buttons -->
<label for="btn_red_group2">Red 2:</label><input id="btn_red_group2" type="radio" name="radio_btn_group2" />
<label for="btn_blue_group2">Blue 2:</label><input id="btn_blue_group2" type="radio" name="radio_btn_group2" />
<label for="btn_yellow_group2">Yellow 2:</label><input id="btn_yellow_group2" type="radio" name="radio_btn_group2" />
<label for="btn_pink_group2">Pink 2:</label><input id="btn_pink_group2" type="radio" name="radio_btn_group2" />
jQuery
// Attaching click event handlers to all radio buttons...
$('input[type="radio"]').bind('click', function(){
// Processing only those that match the name attribute of the currently clicked button...
$('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one...
});
$('input[type="radio"]').bind('deselect', function(){
console.log($(this));
})
Deselection events will trigger only among members of the same radio group (elements that have the same name attribute).
jsFiddle solution
EDIT: In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use onchange event to trigger the handlers. Thanks to Faust for pointing that out.
$('input[type="radio"]').on('change', function(){
// ...
}
You can create a custom "deselect" event relatively painlessly, but as you've already discovered the standard change event is only triggered on the newly checked radio button, not on the previously checked one that has just been unchecked.
If you'd like to be able to say something like:
$("#one").on("deselect", function() {
alert("Radio button one was just deselected");
});
Then run something like the following function from your document ready handler (or put the code directly in your document ready handler):
function setupDeselectEvent() {
var selected = {};
$('input[type="radio"]').on('click', function() {
if (this.name in selected && this != selected[this.name])
$(selected[this.name]).trigger("deselect");
selected[this.name] = this;
}).filter(':checked').each(function() {
selected[this.name] = this;
});
}
Working demo: http://jsfiddle.net/s7f9s/2
What this does is puts a click handler on all the radios on the page (this doesn't stop you adding your own click event handlers to the same radios) that will check if there was a previously selected radio in the same group (i.e., with the same name) and if so trigger a "deselect" event on that radio. Then it saves the just-clicked one as the current one. The "deselect" event is not triggered if you click the already checked radio or if there was no previously checked one. The .filter().each() bit at the end is to make note of which radios are already selected. (If you need to cater for more than one form on the same page having independent radio groups of the same name then update the function above accordingly.)
I found that the simplest way to do this without putting in a new framework to create a deselected event, is to make changing any radio button trigger an update event on all of the radio buttons in its group and then define the behavior you want in the update event.
The downside is that the code in the deselection branch will run even if the radio button was not previously selected. If all you're doing is simple showing, hiding, or disabling UI elements, that shouldn't matter much.
To use your example:
buttons = $('input[name="a"]');
buttons.change(function() {
buttons.trigger('update:groupA');
}).bind('update:groupA', function(){
if(this.checked) {
//Do your checked things
} else {
//Do your unchecked things. Gets called whenever any other button is selected, so don't toggle or do heavy computation in here.
}
});
I think you need to add the change function on the input level, rather than on each radio button.
Try this:
$("input[name='a']").change(function() {
$("input[name='a']").each(function(){
if(this.checked) {
// do something when selected
} else {
// do something when deselected
}
});
});
I think this could be happening because the focus event triggers before the change event so the next radio you click will be focused before the previous checked radio triggers a change event. Don't quote me on this though...
You could do it like this:
var isChecked = function(id) { alert(id + ': ' + $('#' + id).is(':checked')) }
$('input[name="a"]').change(function(){ isChecked('one') })
Demo: http://jsfiddle.net/elclanrs/cD5ww/
You can trigger the 'change' event yourself. It's a bit tricky to avoid radio buttons infinitely triggering 'change' event on each other, but it can be done like this:
$('input[type="radio"]').each(function() {
var name = $(this).attr('name');
var that = this;
$('input[name="'+name+'"][type="radio"]').not(that)
.on('change', function(e, alreadyTriggered) {
if(!alreadyTriggered || alreadyTriggered.indexOf(this) == -1) {
if(!alreadyTriggered) {
alreadyTriggered = [that];
}
alreadyTriggered.push(this);
$(that).trigger('change', [alreadyTriggered]);
}
});
});
Here's the demo of the above code at work.
I found a workaround for my specific case that might help. This works when the "deselect" event can be applied to all radio buttons that aren't selected.
I wanted to:
add a class to the element when the radiobutton was selected, and
remove that class when the button was "deselected".
I happened to find this question, because I had the same problem:
$('input:radio').on('change', function() {
if( $(this).is(':checked') ) {
$(this).addClass('my-class-for-selected-buttons')
} else { // THIS WILL NEVER HAPPEN
$(this).removeClass('my-class-for-selected-buttons')
}
});
But, in my case, the solution was pretty much easier, because I can try to remove the class from all the radio-buttons pretty simply with jQuery, and then add the class to the selected one:
$('input:radio').on('change', function() {
$('input:radio').removeClass('my-class-for-selected-buttons') // Here!
if( $(this).is(':checked') ) {
$(this).addClass('my-class-for-selected-buttons')
}
});
With this simple tweak, I didn't need to find a way to trigger the "deselect" event.
So, if in your case you can apply the event to all the radio buttons that aren't selected, and not only to the one that's just been "deselected", you can use this measure!
Note: I'm using the most recent version of jquery: version 3.4.1. But this should work for older versions as well.
The major challenge here is that the change event is only triggered for the radio button that was checked. The code below confirms this.
$("input[name^='account']").change(function() {
console.log($(this).prop('id') + " was checked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form action='#'>
<input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br>
<input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br>
<input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br>
<input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br>
<input type='text' name='amount' value=''><br>
<input type='submit' value='submit'>
</form>
My Solution: Handle everything inside the change event handler in 3 simple steps:
handle the changes for the currently checked radio button.
attach custom event and handler to all other radio buttons in the same group.
immediately trigger this custom event.
No need to play around with click events here. simple!
var radioBtns = $("input[name^='account']");
radioBtns.change(function() {
// 1. handle changes for the currently checked radio button.
console.log($(this).prop('id') + " was checked");
// 2. attach custom event and handler to all other radio buttons in the same group.
radioBtns.not(':checked').off('deselect').on('deselect', function() {
$(this).each(function(i, e) {
console.log($(e).prop('id') + " was not checked");
});
}).trigger('deselect'); // 3. immediately trigger this custom event.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form action='#'>
<input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br>
<input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br>
<input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br>
<input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br>
<input type='text' name='amount' value=''><br>
<input type='submit' value='submit'>
</form>
I played a bit with the ids.
That is probably an inefficient solution to be fair.
<input type="radio" id="radio-1" name="a" value="initial 1"/>
<input type="radio" id="radio-2" name="a" value="initial 2"/>
let id;
$('input[id*="radio-"]').on('click', (function() {
if (this.id != id && this.checked) {
id = this.id;
this.checked = true;
console.log('selected');
} else if (this.id == id && this.checked) {
id = undefined;
this.checked = false;
console.log('deselected');
}
}));
JSFiddle
hows this for ya?
http://jsfiddle.net/WZND9/6/
$('input').change(function() {
if ($('#one').is(':checked')) {
alert('checked');
} else {
alert('not checked');
}
});
Related
jQuery event for all radiobuttons affected by change of one [duplicate]
Is there an easy way to attach a "deselect" event on a radio button? It seems that the change event only fires when the button is selected. HTML <input type="radio" id="one" name="a" /> <input type="radio" id="two" name="a" /> JavaScript $('#one').change(function() { if(this.checked) { // do something when selected } else { // THIS WILL NEVER HAPPEN // do something when deselected } }); jsFiddle
Why don't you simply create a custom event like, lets say, deselect and let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way. HTML <!-- First group of radio buttons --> <label for="btn_red">Red:</label><input id="btn_red" type="radio" name="radio_btn" /> <label for="btn_blue">Blue:</label><input id="btn_blue" type="radio" name="radio_btn" /> <label for="btn_yellow">Yellow:</label><input id="btn_yellow" type="radio" name="radio_btn" /> <label for="btn_pink">Pink:</label><input id="btn_pink" type="radio" name="radio_btn" /> <hr /> <!-- Second group of radio buttons --> <label for="btn_red_group2">Red 2:</label><input id="btn_red_group2" type="radio" name="radio_btn_group2" /> <label for="btn_blue_group2">Blue 2:</label><input id="btn_blue_group2" type="radio" name="radio_btn_group2" /> <label for="btn_yellow_group2">Yellow 2:</label><input id="btn_yellow_group2" type="radio" name="radio_btn_group2" /> <label for="btn_pink_group2">Pink 2:</label><input id="btn_pink_group2" type="radio" name="radio_btn_group2" /> jQuery // Attaching click event handlers to all radio buttons... $('input[type="radio"]').bind('click', function(){ // Processing only those that match the name attribute of the currently clicked button... $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one... }); $('input[type="radio"]').bind('deselect', function(){ console.log($(this)); }) Deselection events will trigger only among members of the same radio group (elements that have the same name attribute). jsFiddle solution EDIT: In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use onchange event to trigger the handlers. Thanks to Faust for pointing that out. $('input[type="radio"]').on('change', function(){ // ... }
You can create a custom "deselect" event relatively painlessly, but as you've already discovered the standard change event is only triggered on the newly checked radio button, not on the previously checked one that has just been unchecked. If you'd like to be able to say something like: $("#one").on("deselect", function() { alert("Radio button one was just deselected"); }); Then run something like the following function from your document ready handler (or put the code directly in your document ready handler): function setupDeselectEvent() { var selected = {}; $('input[type="radio"]').on('click', function() { if (this.name in selected && this != selected[this.name]) $(selected[this.name]).trigger("deselect"); selected[this.name] = this; }).filter(':checked').each(function() { selected[this.name] = this; }); } Working demo: http://jsfiddle.net/s7f9s/2 What this does is puts a click handler on all the radios on the page (this doesn't stop you adding your own click event handlers to the same radios) that will check if there was a previously selected radio in the same group (i.e., with the same name) and if so trigger a "deselect" event on that radio. Then it saves the just-clicked one as the current one. The "deselect" event is not triggered if you click the already checked radio or if there was no previously checked one. The .filter().each() bit at the end is to make note of which radios are already selected. (If you need to cater for more than one form on the same page having independent radio groups of the same name then update the function above accordingly.)
I found that the simplest way to do this without putting in a new framework to create a deselected event, is to make changing any radio button trigger an update event on all of the radio buttons in its group and then define the behavior you want in the update event. The downside is that the code in the deselection branch will run even if the radio button was not previously selected. If all you're doing is simple showing, hiding, or disabling UI elements, that shouldn't matter much. To use your example: buttons = $('input[name="a"]'); buttons.change(function() { buttons.trigger('update:groupA'); }).bind('update:groupA', function(){ if(this.checked) { //Do your checked things } else { //Do your unchecked things. Gets called whenever any other button is selected, so don't toggle or do heavy computation in here. } });
I think you need to add the change function on the input level, rather than on each radio button. Try this: $("input[name='a']").change(function() { $("input[name='a']").each(function(){ if(this.checked) { // do something when selected } else { // do something when deselected } }); });
I think this could be happening because the focus event triggers before the change event so the next radio you click will be focused before the previous checked radio triggers a change event. Don't quote me on this though... You could do it like this: var isChecked = function(id) { alert(id + ': ' + $('#' + id).is(':checked')) } $('input[name="a"]').change(function(){ isChecked('one') }) Demo: http://jsfiddle.net/elclanrs/cD5ww/
You can trigger the 'change' event yourself. It's a bit tricky to avoid radio buttons infinitely triggering 'change' event on each other, but it can be done like this: $('input[type="radio"]').each(function() { var name = $(this).attr('name'); var that = this; $('input[name="'+name+'"][type="radio"]').not(that) .on('change', function(e, alreadyTriggered) { if(!alreadyTriggered || alreadyTriggered.indexOf(this) == -1) { if(!alreadyTriggered) { alreadyTriggered = [that]; } alreadyTriggered.push(this); $(that).trigger('change', [alreadyTriggered]); } }); }); Here's the demo of the above code at work.
I found a workaround for my specific case that might help. This works when the "deselect" event can be applied to all radio buttons that aren't selected. I wanted to: add a class to the element when the radiobutton was selected, and remove that class when the button was "deselected". I happened to find this question, because I had the same problem: $('input:radio').on('change', function() { if( $(this).is(':checked') ) { $(this).addClass('my-class-for-selected-buttons') } else { // THIS WILL NEVER HAPPEN $(this).removeClass('my-class-for-selected-buttons') } }); But, in my case, the solution was pretty much easier, because I can try to remove the class from all the radio-buttons pretty simply with jQuery, and then add the class to the selected one: $('input:radio').on('change', function() { $('input:radio').removeClass('my-class-for-selected-buttons') // Here! if( $(this).is(':checked') ) { $(this).addClass('my-class-for-selected-buttons') } }); With this simple tweak, I didn't need to find a way to trigger the "deselect" event. So, if in your case you can apply the event to all the radio buttons that aren't selected, and not only to the one that's just been "deselected", you can use this measure!
Note: I'm using the most recent version of jquery: version 3.4.1. But this should work for older versions as well. The major challenge here is that the change event is only triggered for the radio button that was checked. The code below confirms this. $("input[name^='account']").change(function() { console.log($(this).prop('id') + " was checked"); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <form action='#'> <input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br> <input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br> <input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br> <input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br> <input type='text' name='amount' value=''><br> <input type='submit' value='submit'> </form> My Solution: Handle everything inside the change event handler in 3 simple steps: handle the changes for the currently checked radio button. attach custom event and handler to all other radio buttons in the same group. immediately trigger this custom event. No need to play around with click events here. simple! var radioBtns = $("input[name^='account']"); radioBtns.change(function() { // 1. handle changes for the currently checked radio button. console.log($(this).prop('id') + " was checked"); // 2. attach custom event and handler to all other radio buttons in the same group. radioBtns.not(':checked').off('deselect').on('deselect', function() { $(this).each(function(i, e) { console.log($(e).prop('id') + " was not checked"); }); }).trigger('deselect'); // 3. immediately trigger this custom event. }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <form action='#'> <input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br> <input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br> <input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br> <input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br> <input type='text' name='amount' value=''><br> <input type='submit' value='submit'> </form>
I played a bit with the ids. That is probably an inefficient solution to be fair. <input type="radio" id="radio-1" name="a" value="initial 1"/> <input type="radio" id="radio-2" name="a" value="initial 2"/> let id; $('input[id*="radio-"]').on('click', (function() { if (this.id != id && this.checked) { id = this.id; this.checked = true; console.log('selected'); } else if (this.id == id && this.checked) { id = undefined; this.checked = false; console.log('deselected'); } })); JSFiddle
hows this for ya? http://jsfiddle.net/WZND9/6/ $('input').change(function() { if ($('#one').is(':checked')) { alert('checked'); } else { alert('not checked'); } });
javascript confirm when checking a checkbox by clicking on the label
I have a checkbox on a form that does something dangerous. So, I want to make sure the user is really sure when they check this item, but I don't want to warn them if they're unchecking the checkbox. My issue is this works fine if they click on the actual checkbox to uncheck it, but not the text of the label. http://jsfiddle.net/j2ppzpdk/ function askApply() { if (document.getElementById("apply").checked) { var answer = confirm("Are you sure about that?"); if (!answer) { document.getElementById("apply").checked = false; } } } <form> <label onclick="askApply();"> <input type="checkbox" name="apply" id="apply" value="1" /> Apply </label> </form>
Some notes: Better add the event listener to the element that changes (the checkbox), not its label. Better listen to change event instead of click. For example, the checkbox could be changed using the keyboard. Better avoid inline event listeners. You can use addEventListener instead. document.getElementById('apply').addEventListener('change', function() { if(this.checked) { var answer = confirm("Are you sure about that?"); if (!answer) { document.getElementById("apply").checked = false; } } }); <form> <label> <input type="checkbox" name="apply" id="apply" value="1" /> Apply </label> </form>
How to run a function from radio button mouseup event?
I'm trying to use a pair of radio buttons to start/stop an automated horizontal scroller. I've tried several jquery techniques that I found on SO, but I haven't been able to get them to work. Here's my latest attempt: $( "#radAutoScroll0" ).mouseup(function() { scrollTimer(); }); function scrollTimer(){ if($("#radAutoScroll0").is(':checked')){ // scroller code..... } } <div class="scrollDiv"> <label for="autoScroll" class="autoScrollLabel">Auto Scroll</label><br /> <label for="radAutoScroll0" class="labAutoScroll"> <input type='radio' name='radAutoScroll' id='radAutoScroll0' class="rad1" checked="checked" value='on'/>On </label> <label for="radAutoScroll1" class="labAutoScroll"> <input type='radio' name='radAutoScroll' id='radAutoScroll1' class="rad1" value='off'/>Off </label> </div>
Or try to use 'click' event on your label as they wrap the radio-button: $(document).on('click', '.labAutoScroll', function(event) { var thisButton = $(this).prop('for'); if (thisButton == 'radAutoScroll0') { } else { } }); If you have more than 2 radio buttons you can use switch(thisButton) to separate your cases.
Use the change event, and bind it to both radio buttons (using the labAutoScroll class) so it fires when you click either of them. $('.labAutoScroll').change(function() { if($("#radAutoScroll0").is(':checked')){ // scroller code..... } });
jQuery addClass when a radio button in a group is selected
I have the following code: var selectedMarkerClass = 'was-selected'; $('.group_1').change(function() { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1').length) { $('#2').removeClass('red'); } }); Here is the HTML in question: <input class="single_text_input group_1" type="text" name="primary_referral" /> <input class="single_text_input group_1" type="text" name="secondary_referral" /> <input class="group_1" type="radio" name="referral_open" value="Yes" /> Yes <input class="group_1" type="radio" name="referral_open" value="No" /> No <span id="2" class="red">Referral Group</span> What is happening now is that both radio buttons in the group have to be changed in order for the class to be removed from the span. I would like it to work where only one of the radio buttons in the group has to be changed.
Use the click event not change event. $('.group_1').click(function() { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1').length) { $('#2').removeClass('red'); } }); Update: if ($('.' + selectedMarkerClass).length == $('.group_1').length) Is tripping you up. You are removing the red class only if the selected class has been added to each radio and you can only add the selected class if you click each radio. A better way would be: $('.group_1').click(function() { $('#2').removeClass('red'); }); Less code is often times better. You can't unselect a radio. So any click on the radios ensures at least one is clicked.
Try it with click event instead. You see the change take place after the second click because change gets fired after the first radio button loses focus.
After both radio button changed, $('.' + selectedMarkerClass).length == 2 and $('.group_1').length == 4 because you are using .group_1 class for radio buttons and as well as for input[type=text] too. need filter your radio button, use "[name=referral_open]", var selectedMarkerClass = 'was-selected'; $('.group_1').change(function () { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1[name=referral_open]').length) { $('#2').removeClass('red'); } });
problem with jquery for add cart button
hi i have a problem with displaying amount.i have the page called make payment in this page i made three radio buttons, if i click the button that amount must add with addcart like a product. <form method="post" form name="make_payment_frm" action="module/make-payment-module.php" onsubmit="return show_make_payment_validation();" > <form id='theForm'> <input type="hidden" name="totalamount" id="totalamount" value="1" /> input type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" /> input type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)"/> input type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)"/> div id="finalamount"> /div> i think that problem is my js script. if i click that button there is no response. how do i solve that problem you guys can give me any idea $(document).ready(function() { $(".cart :radio[name='rmr']").add(".cart :radio[name='rmr']").each(function() { $(this).click(function() { $(".cart :radio[name='rmr']").add(".cart :radio[name='rmr']").each(function() { $(this).attr("checked", false); }); $(this).attr("checked", true); }); }); }) function updatePayment(val) { $("<p/>").html("updatePayment(" + val + ")").appendTo(document.body); } thanks.have a nice day
I have no idea why you seem to be implementing the selecting and un-selecting of radio buttons in jQuery, surely HTML will handle that correctly for you. However if you are using jQuery, do away with those onclick attributes since that is the benefit of jQuery and achieve the same result as follows: $(function() { $('.cart :radio[name="rmr"]').change(function() { if ($(this).is(':checked')) updatePayment(this.value); }); }); This will attach a change event to every radio button input with the attribute name="rmr". Thus when the client clicks a new radio button, the value of two radio buttons will change, and the one that is then selected will call the updatePayment function with its value.