I need to programmatically check a radio button given its value. The form has an id and the input type obviously has a name (but no id). The only code I managed to get working so far is:
$('input[name=my_name]:eq(1)').attr('checked', 'checked');
But I'd like to be able to check it by explicitly providing the value.
So you want to select the radio which has a particular value:
$('input[name=my_name][value=123]').attr('checked', true); // or 'checked'
Below code worked with me, if I am assigning an ID to the radio button:
<input type="radio" id="rd_male" name="gender" value="Male" />
<input type="radio" id="rd_female" name="gender" value="Female" />
$('#rd_male').prop('checked', true);
You should use prop instead of using attr . It's more recommended
$('input[name=my_name][value=123]').prop("checked",true)
In order to select the radio button programmatically, you can call a jQuery trigger or
$(".radioparentclass [value=radiovalue]")[0].click();
$('input[name=field]:eq(1)').click();
Note : field = radio button name property
Recommend use .click()
The other solution that only change radio option property or attribute
will NOT trigger radio event, you have to manually call radio event.
$("#your_radio_option_ID_here").click()
Related
I have the code to uncheck radio button, but the problem is, its not happening in one click when the radio button is checked, I am fetching the value of radio button as checked from mysql, so the default value of radio button is checked and when I click on the radio button the value should uncheck upon single click but my code is making it happen on double click. How do I make it happen with single click?
var check;
$('input[type="radio"]').hover(function() {
check = $(this).is(':checked');
});
var checkedradio;
function docheck(thisradio) {
if (checkedradio == thisradio) {
thisradio.checked = false;
checkedradio = null;
}
else {checkedradio = thisradio;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="check" value="check" onClick="javascript:docheck(this);" checked="checked"/>
Radios by design are meant to be used in a group (https://html.spec.whatwg.org/#radio-button-state-(type=radio)) - a group of 2 or more radios should form a group to allow the user to pick a value from the selection in that group. By design the radio group behaviour is this - once a selection is made (either by the user or programatically), that choice sticks, and there is no way to undo it, other than choose another radio option from the group. You'll see in your example, that without the JavaScript bit, if you by default uncheck the radio, then check it manually, you won't be able to uncheck it again. This is how it's supposed to work.
The rule of thumb should be that solving a problem on the backend should not come at the expense of the front-end, as it negatively impacts the user-experience, and will cause problems to the user. If you for any reason HAVE TO stick with such a bad UX solution, here is a way to hack your radio to act like a checkbox, but it is seriously not advised, and you should change your backend to use checkboxes instead.
Here is the radio hack (and a native checkbox input that should be used instead):
var myRadio = $('input[type="radio"]:checked');
myRadio.on('click', function() {
if (myRadio.attr('checked')) {
myRadio.removeAttr('checked');
myRadio.prop('checked', false);
} else {
myRadio.attr('checked', 'checked');
myRadio.prop('checked', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>This works, but it's bad UX, so avoid!</b><br>
<input type="radio" name="check" value="check" checked />
<hr>
<b>Use this instead!</b>
<br>
<input type="checkbox" name="real-check" value="real-check" checked />
You'll see that the jQuery selector is deliberately set to only pick the "checked" radio, so the JavaScript solution only takes over the native behaviour if the radio is checked by default. As soon as the radio is not checked by default, you'll see how the browser forces your selection once it's checked manually - this is a tell tale sign that you're trying to deviate from the expected behaviour.
You'll also see that the checkbox natively works - without the need for JavaScript or jQuery.
RobertP raised an interesting point about the user experience, or in IT-talk: "UX". In some cases it is mandatory that a single option needs to be clicked. This is exactly what radio buttons were made for. However, I have come across cases, where a "none" selection should also be offered. For these cases you could simply supply an extra radio button with the option "none" OR you could make the radio buttons "unselectable" again. This seems to go against the intended radio button behaviour. However, as it is possible to start out with no radio buttons being selected, why should it not be possible to return to this state after, maybe, the user had clicked on an item prematurely?
So, with these considerations in mind I went ahead and put together a way of doing what OP had in mind. I extended the example a little bit by including further radio button options:
$.fn.RBuncheckable=function(){ // simple jQuery plugin
const rb=this.filter('input[type=radio]'); // apply only on radio buttons ...
rb.each(function(){this.dataset.flag=$(this).is(':checked')?1:''})
.on('click',function(){
if (this.dataset.flag) $(this).prop('checked',false) // uncheck current
// mark whole group (characterised by same name) as unchecked:
else rb.filter('[name='+this.name+']').each(function(){this.dataset.flag=''});
this.dataset.flag=this.dataset.flag?'':1; // invert flag for current
});
return this;
}
$('input').RBuncheckable(); // apply it to all radio buttons on this page ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Two groups of radio buttons with "uncheck" option:</h4>
<input type="text" value="This input field is unaffected">
<p>group one:</p>
<label><input type="radio" name="check" value="a" checked /> Option A</label><br>
<label><input type="radio" name="check" value="b"/> Option B</label><br>
<label><input type="radio" name="check" value="c"/> Option C</label>
<p>group two:</p>
<label><input type="radio" name="second" value="d"/> Option D</label><br>
<label><input type="radio" name="second" value="e"/> Option E</label><br>
<label><input type="radio" name="second" value="f" checked/> Option F</label>
In the .each() loop I collect the initially checked state for all selected radio buttons. I store the individual checked state in a data attribute "flag" for each radio button.
The click event handler function then picks up this data flag and decides whether to step into action by either removing the checked state from the current element or simply resetting the flag data-attributes for the whole group (characterised by having the same name as the currently clicked one). In a last operation it then inverts the flag state for the current element again. As all data attributes are stored as strings, the values 1 and "" are "truthy" and "falsy" values that can be directly tested.
This results in exactly the behaviour you were looking for. I hope ;-)
By having the functionality packaged in a little jQuery plugin it can now be applied to any jQuery object directly.
I need to know if user clicked to already checked radio or he made a new choice.
Now I detect it via "focus", "click" and "change" events combination (store old value in "focus", and compare it with current in "click" or "change" to detect and handle click to already checked radio).
Just to clarify: I cant store previous state in click handler, because I could not get the the initial state here; or "focus+click" or "load+(prev)click+click";
But it looks like a hack for me, and I assume that there is a more straight way to do this using built-in jquery features, using just one event handler.
Is there something like this?
Thanks in advance!
Use mousedown as #Bukent Vural suggests.
Get the current value before change with $('input[name=test]:checked').val();,
where 'test' is the name of your radio inputs.
Take a look at this JSFiddle.
EDIT
If you want to detect label clicks as well, a second event handler needs to be added:
$('label').click(function() {
labelID = $(this).attr('for');
$('#'+labelID).trigger('mousedown');
});
Check the updated JSFiddle.
You could also keep a copy of the checked value in a data attribute which you then update accordingly in the click handler:
$('input[name=test]').click(function(){
var previous = $('input[name=test][data-checked=true]')[0];
console.log(`previous: ${previous.id}`);
console.log(`this: ${this.id}`);
// the button was already checked so nothing needs to happen
if (this.id === previous.id) {
return;
}
// update data-checked: add attribute to the current button, remove for the rest
$(this).attr('data-checked', 'true');
$('input[name=test]:not(:checked)').removeAttr('data-checked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test1" type='radio' name='test' value='First' checked data-checked='true'>
<label for="test1">First</label><br>
<input id='test2' type='radio' name='test' value='Second'>
<label for="test2">Second</label><br>
<input id='test3' type='radio' name='test' value='Third'>
<label for="test3">Third</label><br>
I'm using the iCheck framework and I have two inputs
<input name="group" id="id1" type="radio" checked>
<input name="group" id="id2" type="radio">
<input name="group" id="id3" type="radio">
<input name="group" id="id4" type="radio">
On click I call an ajax function. If something fail, I want to set back the checked attribute to the previously selected input.
var currentChecked = $("input[name='group']:radio:checked");
$("input[name='group']:radio").each(function() {
$(this).on('ifChecked', function(){
$.ajax({
url: "/ajax/something/"
})
.done(function (data) {
currentChecked = $(this);
})
.fail(function (data) {
$(this).removeAttr('checked');
currentChecked.prop('checked', true);
});
});
});
But this will not reset the checked checkbox. There is something I don't see from the iCheck framework? Any solution?
Actually in case of iCheck You need to update the iCheck to reflect the changes on Jquery.
You can update using iCheck('update')
$(this).iCheck('update');
After checked or unchecked the radio button using jquery.
Another Solution just check or uncheck the iCheck using his predefined function.
<input name="group" id="id1" type="radio" checked>
If the above one is your radio button you can use the code in jquery section like below
$('#id1').iCheck('uncheck'); //To uncheck the radio button
$('#id1').iCheck('check'); //To check the radio button
In this case no need to use the iCheck('update')
jQuery iCheck works bit different from the way you expect.
When you initialize a checkbox or radio button, it picks up the status/value of the control and builds the look and feel of that state. That is all. Then it never checks your control value or any update to its attributes.
So the only way to uncheck your checkbox in the Ajax failure event, is by using the functions exposed by the plugin.
You should use following in your ajax fail event to change the state back to previous
$(this).iCheck('toggle');
or you can change the html attributes and refresh the control like below
$(this).removeAttr('checked');
currentChecked.prop('checked', true);
$(this).iCheck('update'); — apply input changes, which were done outside the plugin
Below solution worked for me in iCheck v1.0.2.
You can check iCheck radio by filtering radio button group like below
Using 'id' of element
$('input:radio[name="group"]').filter('[id="id1"]').iCheck('check');
Using 'value'
$('input:radio[name="group"]').filter('[value="id1"]').iCheck('check');
you can replace 'id' or 'value' dynamically base on your requirement/functionality.
and you can change 'check' or 'uncheck' inside .iCheck('check').
//this will update all iCheck fields inside the selected form
$('#form_id :radio').iCheck('update');
I want to show some input checkbox inside a form only if a certain other checkbox is checked.
I´ve read about .show() and .hide() but I want to do it changing the css selector.
My problem is that the hidden selector isn't hidden at all: It is printed out without any regard of the checkbox.
Please note that this is just a test, I'm learning jQuery and wanted to try it out.
This is what I've tried (JSfiddle)
HTML FORM:
<form name="ejemplo">
<input type="checkbox" name="checkbox1" id="idCheckbox1" value="check" checked>Sí?
<input type="checkbox" name="checkbox2" id="idCheckbox2" value="check">No
<div id="ocultar">
<input type="checkbox" name="checkbox3" id="idCheckbox3" value="check">Tal Vez</div>
</form>
JS
//Usamos jQuery para mostrar un elemento condicionalmente
if ( $("input:checkbox[id=idCheckbox2]:checked") )
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
Since id is unique you can use
$("#idCheckbox2")
instead of
$("input:checkbox[id=idCheckbox2]")
To check if the checkbox is checked, you can use .is():
if($("#idCheckbox2").is(":checked"))
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
You also need to use .change() event to keep track when your checkbox has been changed and shorten your code using ternary operator:
$('#idCheckbox2').change(function () {
$("#ocultar").css("display", this.checked ? 'inline' : "none");
}).change();
The .change() at the end is used to trigger the change() event on page load and execute the code if your checkbox has been checked by default.
Fiddle Demo
You need to use a change event handler so that the display properties will up updated based on checking/unchecking of the checkbox
$('#idCheckbox2').change(function(){
$("#ocultar").css("display", this.checked ? 'inline':"none");
}).change();//used to set the initial state based on checkbox value
Demo: Fiddle
You can even use .toggle() to simplify the code like in this fiddle
So visually they have the correct behavior. Only 1 radio button in a set is checked and the checkbox checks/unchecks in reaction to pressing it but it seems when checking the status of the inputs in the console that isn't the case. So I have:
<input id="addon-fixed" type="checkbox" value=True checked />
<input id="addon-type0" name="addon-type" type="radio" checked/>Addon<br>
<input id="addon-type1" name="addon-type" type="radio"/>Cutout
But regardless of what I click the behavior is always the same
$('#addon-fixed').attr('checked') // always there
$('#addon-type0').attr('checked') // always there
$('#addon-type1').attr('checked') // always undefined
Use prop() instead of attr()
$('#addon-fixed').prop('checked')
Checking or unchecking the checkbox changes the checked property, it doesn't change the element's attribute.
if you want to check whether it is checked or not:
Use this...
if($('#addon-fixed').is(':checked')){
//checked
}else {
//unchekced
}
hope this will help you...