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.....
}
});
Related
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');
}
});
I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.
Here is the js code:-
$(".panel-body").on("click", '#select_none', function(event) {
$("input[name='nodelevel']:checkbox").each(function() {
this.checked = false;
});
});
Make sure there is only one parent with .panel-body class name. maybe there is two of .panel-body and it makes this happen. like this:
<div class="panel-body">
...
<div class="panel-body">
...
<!-- your selectors -->
</div>
</div>
try stoppropagation to avoid second parent event listener call:
$(".panel-body").on("click", '#select_none', function(event) {
event.stopPropagation();
$("input[name='nodelevel']:checkbox").each(function() {
this.checked = false;
});
});
EDIT : and of course you can add listener to document instead of .panel-body :)
Example:
<input class="itemClass" type="checkbox" name="Items" value="Bike"> I have a bike<br>
<input class="itemClass" type="checkbox" name="Items" value="Car" checked> I have a car<br>
<button name="submit" onclick="getValue()" value="Submit">
Then:
function getValue() {
var id;
var name;
var temp = [];
$('.itemClass').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
console.log(sThisVal);
if (this.checked) {
// $("input[name=Items]:checked").map(function () {
temp.push(sThisVal);
}
});
console.log(temp);
$('.itemCheckboxClass').prop('checked', false);
}
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>
Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});
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');
}
});