I am trying to disable all of the radio buttons in the same class when another is checked. This function works with checkboxes, but not when I use radio buttons. Any help would be appreciated.
https://jsfiddle.net/neilcosby123/qssvzap4/1/
function radcheck(){
var ra = document.getElementById("main")
if(ra.checked){
$(".radioclass").prop("disabled", true);
$(".radioclass").attr("checked", false);
}
}
$(function(){
var $radios = $('.radioclass');
$('#main').on('click', function(){
$radios.prop('disabled', this.checked).prop('checked', false);
});
});
It's hard to write without any context (like why do you want to do this?).
I assume that what you need is this:
$("#main").change(function() {
var isChecked = $(this).is(":checked");
$(".radioclass")
.prop("disabled", isChecked)
.prop("checked", !isChecked);
});
Here's how to do it with vanilla js, since the jquery isn't really critical, and honestly, I feel like it is overkill for this situation.
function radcheck(){
var ra = document.getElementById("main");
if(ra.checked){
var radios = document.querySelectorAll('.radioclass');
for(var i=0;i<radios.length;i++){
radios[i].checked = false;
radios[i].disabled = true;
}
}
}
If you want them to toggle, you could do the same loop but instead do:
radios[i].checked = !radios[i].checked;
radios[i].disabled = !radios[i].disabled;
actually in ur given fiddle. you have not linked the jquery library. check the fiddle https://jsfiddle.net/stdeepak22/e9zeL6eL/1/
$(document).ready(function () {
$('#main').click(function () {
if ($(this).prop('checked')) {
$(".radioclass").each(function () {
$(this).prop("disabled", true);
$(this).prop("checked", false);
//$(".radioclass").attr("checked", false);
});
}
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.