简体   繁体   English

检查单选按钮,是否选择了父div?

[英]check radio button whe parent div is selected?

I have a radio button that I would be like to be selectable if the user clicks the div thats its inside of. 我有一个单选按钮,如果用户单击其内部的div,我希望可以选择它。 I have a click event for the div but I can't seem to get the radio button to check. 我有一个div的click事件,但似乎无法检查单选按钮。

heres my code: 这是我的代码:

var new_div = document.createElement('div');
        new_div.setAttribute('id', 'controlDiv');
        new_div.setAttribute('class', 'ansClass');
var newAnswer = document.createElement('input');
        newAnswer.setAttribute('type', 'radio');
        newAnswer.setAttribute('name', 'choice');
        newAnswer.setAttribute('class', 'radioButton');
        $(newAnswer).attr("id", "button"+j);


        var newLabel = $("<label>", {id: "label"+j, class: "ansLabel", text: "answer"+j});


        $(new_div).append(newAnswer); 
        $(new_div).append(newLabel);



$( "#controlDiv" ).click(function() {
    var radButton = $(this).find('input[type=radio]');
    radButton.click();
      //  $(radButton).attr("checked", "checked");
});

Try .prop() instead of .attr() 尝试使用.prop()而不是.attr()

$( "#controlDiv" ).click(function() {
    var radButton = $(this).find('input[type=radio]');
    $(radButton).prop("checked", true);
});

I would have a similar answer to Arun's, except modified a little to allow for unchecking as well: 除了对Arun进行了一些修改以允许取消选中之外,我将获得与Arun相似的答案:

$('#controlDiv').click( function(){
  var radButton = $(this).find('input[type=radio]');
  if(radButton).is(':checked')){
    $(radButton).removeAttr('checked');
  } else {
    $(radButton).attr('checked', 'checked');
  }
});

I would maybe go a step further and provide the radio button with a specific ID. 我可能会更进一步,并为单选按钮提供特定的ID。 If it's one of many, try to go with a class. 如果是其中之一,请尝试上一堂课。 This just gives you more specificity in your coding. 这只是使您的编码更具特异性。

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

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