I have a radio button group like this:
<div data-role="fieldcontainer">
<fieldset data-role="controlgroup" data-type="horizontal" name="optRestriction" id="optRestriction">
<legend>Restriction</legend>
<input type="radio" name="chkRestriction" id="chkRed" value="R" class="custom" />
<label for="chkRed">Red</label>
<input type="radio" name="chkRestriction" id="chkYello" value="Y" class="custom" />
<label for="chkYello">Yellow</label>
<input type="radio" name="chkRestriction" id="chkGreen" value="G" class="custom" />
<label for="chkGreen">
I am trying to set the selected value after retrieving values from the serve API.
I have tried various ways like below:
$("input[name=chkRestriction][value=" + data.rows[0].restrictionCd + "]").prop('checked', true).trigger('change');
$("input[type='radio']:eq(" + data.rows[0].restrictionCd + ")").attr("checked", "checked");
$("input[type='radio']").checkboxradio("refresh");
$("input[name=chkRestriction][value=" + data.rows[0].restrictionCd + "]").prop('checked', true).trigger('change');
$('[name="chkRestriction"]').val([ data.rows[0].restrictionCd ]);
But none seem to work. A demo fiddle is here
Appreciate any suggestions in advance.
Set attribute "checked" and call refresh.
$('input:radio[name="chkRestriction"]').filter('[value="R"]').attr("checked",true).checkboxradio("refresh");
Jsfiddle - https://jsfiddle.net/of7uvbwh/3/
Set/unset the value of each radio button in a loop like this this:
var valToSet = myVal; // myVal is value to set from API
$('#optRestiction input').each(function(){
var $this = $(this)
if($this.val() == valToSet) {
$this.prop('checked', true);
}
else {
$this.prop('checked', false);
}
});
The 'changed' event fires when one of your inputs changes state. Triggering it will accomplish nothing unless you have defined a handler for the 'changed' event for that input.
Try this.
$('input:radio[name="chkRestriction"]').filter('[value="R"]').attr("checked",true).checkboxradio().checkboxradio("refresh");
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');
}
});
Project Focus
Toggle Checkbox(es)
Special Requirement
Need to bind the new(dynamically) added div.id container that holds these checkboxes. Note: this div.id has been dynamically generated (client-side).
Status
My Working Fiddle successfully toggles between 1(one) or 0(none) checkboxes.
The HTML
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>
Working Script
var checkboxes;
checkboxes = $("input[name^=iso_01]").change(function (e) {
checkboxes.not(this).prop("checked", false);
}
});
Desired Result
I'm having trouble with syntax for updating .click() to .on("click","input..." see Bound Fiddle
Updated Script
var checkboxes;
checkboxes = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
checkboxes.not(this).prop("checked", false);
}
});
Your issue is,
checkboxes = $("#bind_id").on
is not doing what you think it is doing. It is not storing all the matched nodes.
Try this instead:
In the callback, change
checkboxes.not(..)
to
$('input[name^=iso_01]').not(this).prop("checked", false);
Working fiddle
Or if they are loaded dynamically, you can use $('#bind_id').find('input[name^=iso_01]')
This is not what checkboxes are for. You should be using radio buttons:
<input type="radio" name="example" value="1" id="1">
<label for="1">one</label>
<input type="radio" name="example" value="2" id="2">
<label for="2">two</label>
The problem is checkboxes is the #bind_id element, not the checkboxes. You would need to find the children from that element, to get the child checkbox elements.
Working Example:
var wrapper;
wrapper = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
wrapper.find("input[name^=iso_01]").not(this).prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>
I've got the following code to trigger a click event on some radio buttons! but it doesn't get fired! can any one help me with this!
CODE :
$("#inline_content input[name='type']").click(function(){
if($('input:radio[name=type]:checked').val() == "walk_in"){
$('#select-table > .roomNumber').attr('enabled',false);
}
});
RADIO BUTTONS
<form class="type">
<input type="radio" name="type" checked="checked" value="guest">In House</input>
<input type="radio" name="type" value="walk_in">Walk In</input>
</form>.
Update
Tried onChange() too but not working.
It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/
$("#inline_content input[name='type']").click(function(){
alert('You clicked radio!');
if($('input:radio[name=type]:checked').val() == "walk_in"){
alert($('input:radio[name=type]:checked').val());
//$('#select-table > .roomNumber').attr('enabled',false);
}
});
There are a couple of things wrong in this code:
You're using <input> the wrong way. You should use a <label> if you want to make the text behind it clickable.
It's setting the enabled attribute, which does not exist. Use disabled instead.
If it would be an attribute, it's value should not be false, use disabled="disabled" or simply disabled without a value.
If checking for someone clicking on a form event that will CHANGE it's value (like check-boxes and radio-buttons), use .change() instead.
I'm not sure what your code is supposed to do. My guess is that you want to disable the input field with class roomNumber once someone selects "Walk in" (and possibly re-enable when deselected). If so, try this code:
HTML:
<form class="type">
<p>
<input type="radio" name="type" checked="checked" id="guest" value="guest" />
<label for="guest">In House</label>
</p>
<p>
<input type="radio" name="type" id="walk_in" value="walk_in" />
<label for="walk_in">Walk in</label>
</p>
<p>
<input type="text" name="roomnumber" class="roomNumber" value="12345" />
</p>
</form>
Javascript:
$("form input:radio").change(function () {
if ($(this).val() == "walk_in") {
// Disable your roomnumber element here
$('.roomNumber').attr('disabled', 'disabled');
} else {
// Re-enable here I guess
$('.roomNumber').removeAttr('disabled');
}
});
I created a fiddle here: http://jsfiddle.net/k28xd/1/
Personally, for me, the best solution for a similar issue was:
HTML
<input type="radio" name="selectAll" value="true" />
<input type="radio" name="selectAll" value="false" />
JQuery
var $selectAll = $( "input:radio[name=selectAll]" );
$selectAll.on( "change", function() {
console.log( "selectAll: " + $(this).val() );
// or
alert( "selectAll: " + $(this).val() );
});
*The event "click" can work in place of "change" as well.
Hope this helps!
A different way
$("#inline_content input[name='type']").change(function () {
if ($(this).val() == "walk_in" && $(this).is(":checked")) {
$('#select-table > .roomNumber').attr('enabled', false);
}
});
Demo - http://jsfiddle.net/cB6xV/
Seems like you're #inline_content isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.
(made you a jsfiddle, works after adding a parent <div id="inline_content">: http://jsfiddle.net/J5HdN/)
put ur js code under the form html or use $(document).ready(function(){}) and try this.
$('#inline_content input[type="radio"]').click(function(){
if($(this).val() == "walk_in"){
alert('ok');
}
});
I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')
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');
}
});