I have this code to check/uncheck a radio button onclick.
I know it is not good for the UI, but I need this.
$(\'#radioinstant\').click(function() {
If you're still up for more answers i have found that this works with all radio buttons:
<script type="text/javascript">
jQuery(document).ready(function ($){
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent =
function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck =
function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val){
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
});
</script>
This function will add a check/unchecked to all radiobuttons
jQuery(document).ready(function(){
jQuery(':radio').click(function()
{
if ((jQuery(this).attr('checked') == 'checked') && (jQuery(this).attr('class') == 'checked'))
{
jQuery(this).attr('class','unchecked');
jQuery(this).removeAttr('checked');
} else {
jQuery(this).attr('class','checked');
}//or any element you want
});
});
Having tested some of the above solutions which did not work for me 100%, I decided to create my own. It creates new click listeners after a radio button is clicked:
/**
* Radio select toggler
* enables radio buttons to be toggled when clicked
* Created by Michal on 09/05/2016.
*/
var radios = $('input[type=radio]');
/**
* Adds click listeners to all checkboxes to unselect checkbox if it was checked already
*/
function updateCheckboxes() {
radios.unbind('click');
radios.filter(':checked').click(function () {
$(this).prop('checked', false);
});
radios.click(function () {
updateCheckboxes();
});
}
updateCheckboxes();
Improved version of answer from Jurrie
$('#myRadio').off('click').on('click', function() {
if ($(this).data('checked')) {
$(this).removeAttr('checked');
$(this).data('checked', false);
} else {
$(this).data('checked', true);
}
});
Live Demo
$(document).on("click", "input[type='radio']", function(e) {
var checked = $(this).attr("checked");
if(!checked){
$(this).attr("checked", true);
} else {
$(this).removeAttr("checked");
$(this).prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" id="radio" /> <label for="radio">Radio</label>
DiegoP,
I was having the same trouble, until I realized that the check on the box doesnt go off until the attribute is removed. That means even if checked value is made false, it will remain there.
Hence use the removeAttr() function and remove the checked attrib and it WILL DEFINITELY WORK.