单击整个元素以注册单选按钮值

Clicking on entire element to register radio button value

我希望能够单击整个元素,而不仅仅是单选按钮和文本,以便注册与单选按钮关联的值。

<div class='btn'>
<input id = '4' class='btn4' type="radio" name='1' value='' >    
<label for = '4' class="label4">Question populated from jQuery goes here
</label></div>

当我用标签包裹输入时,我丢失了 jQuery 放在元素中的文本。

我必须填充文本的函数是...

function populateQuestion(index) {
if (currentQuestion <=9){
$('.q_question').html(questionsArray[index]['question']);
for (var i = 0; i < 8; i++) {
    $('.jumbotron').html('');
    $('.btn' + (i + 1)).val(questionsArray[index]['choices'][i]).prop('checked', false);
  $('.label' + (i + 1)).html(questionsArray[index]['choices'][i]);
}
} else{ quizComplete(correctAnswers)}
}
populateQuestion(currentQuestion);

您可以为外部 div 注册一个点击事件并执行您想要执行的任何代码。

$(function(){

  $("div.btn").click(function(e){
     e.preventDefault();
     alert("clicked");
     var _this=$(this);
     var radio = _this.find("input[type='radio']");
     //Do something now
     alert('id:'+radio.attr("id"));  //Id of radio button
     alert('value:'+radio.val());    //value of radio button
  });

});

Here 是工作样本。

有趣的小问题。我尝试在 jQuery 的一行中完成此操作,但很快意识到由于正在更改的元素位于容器内,因此尝试单击它们会重置它们(有效地使它们无法单击)。解决方案是在 CSS 中的容器顶部添加一个不可见的伪元素,这样您就无法实际单击单选按钮(或标签)。

$('div.btn').on('click', function() {
  $(this).children('input').prop('checked', !$(this).children('input').prop('checked'));
})
.btn {
  border: 1px solid red;
  padding: 12px;
  position: relative;
}
.btn::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='btn'>
  <input id='4' class='btn4' type="radio" name='1' value=''>
  <label for='4' class="label4">Question populated from jQuery goes here
  </label>
</div>