0

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");
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
Will Tuttle
  • 450
  • 1
  • 11
  • 33

2 Answers2

5

Try .prop() instead of .attr()

$( "#controlDiv" ).click(function() {
    var radButton = $(this).find('input[type=radio]');
    $(radButton).prop("checked", true);
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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.

alexjewell
  • 31
  • 1
  • 6
  • Thanks this would work, but a have my buttons in groups of 4 so they deselect automatically when another is pressed. – Will Tuttle Nov 14 '13 at 00:54