简体   繁体   中英

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. I have a click event for the div but I can't seem to get the radio button to check.

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()

$( "#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:

$('#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. If it's one of many, try to go with a class. This just gives you more specificity in your coding.

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.

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