简体   繁体   English

使用jQuery检查无线电时,检查是否检查无线电不起作用

[英]Checking if radio is checked doesn't work when the radio is checked using jQuery

I need to dynamically set textarea as required or not but it doesn't want to work properly. 我需要根据需要动态设置textarea,但它不想正常工作。 JQuery check it itself but then can't check if it's checked or not. JQuery检查它本身,但然后无法检查它是否被检查。 But when you clicked inside the second radio, the textarea is always required. 但是当你在第二个收音机里面点击时,总是需要textarea。 I tried many times to make it works but it's still buggy. 我尝试了很多次才能使它有效,但它仍然有问题。 I have added "attr" and "removeAttr" because I read on stackoverflow that sometimes '.prop('required',false);' 我添加了“attr”和“removeAttr”因为我在stackoverflow上读到了有时'.prop('required',false);' doesn't work but still no luck. 不行,但仍然没有运气。

I made a fiddle with my problem. 我弄错了我的问题。 jsFiddle 的jsfiddle

$(".parent-div").click(function() {
    $(this).next().slideToggle();
    var a = $(this).next();
    $('.child-div').not(a).slideUp();
    $(this).find("input").prop( "checked", true );
});
$("#my-radio").change(function() {
if(this.checked) {
    $("#my-textarea").prop('required',true);
$("#my-textarea").attr('required');
}
else {
    $("#my-textarea").prop('required',false);
$("#my-textarea").removeAttr('required');
}
});

You dont need the change event of #my-radio . 你不需要#my-radio的改变事件。 You can do it in .parent-div click event like following. 您可以在.parent-div点击事件中执行此操作,如下所示。

$(".parent-div").click(function () {
    $(this).next().slideToggle();
    var a = $(this).next();
    $('.child-div').not(a).slideUp();

    //i have added this
    var checkbox = $(this).find("input");
    checkbox.prop("checked", true);
    $("#my-textarea").prop('required', checkbox.val() == 'second');
});

UPDATED FIDDLE 更新后的

Thank you, Azim . 谢谢, 阿齐姆 User adeneo gave me also a solution, you can find it here: https://jsfiddle.net/h8bwqpyb/6/ 用户adeneo也给了我一个解决方案,你可以在这里找到它: https//jsfiddle.net/h8bwqpyb/6/

$(".parent-div").click(function() {
$(this).next().slideToggle();
var a = $(this).next();
$('.child-div').not(a).slideUp();
var inp = $(this).find("input").prop("checked", true);
$("#my-textarea").prop('required', inp.attr('id') === 'my-radio');
});

Both solutions work great but I finally choose the solution of adeneo because it doesnt' use 'value' to work. 这两种解决方案都很有效,但我最终选择了adeneo的解决方案,因为它没有'使用'价值'来工作。

Many thanks to both you, guys! 非常感谢你们,伙计们! Have a nice day! 祝你今天愉快! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM