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

Clicking on entire element to register radio button value

本文关键字:注册 单选按钮 元素 单击      更新时间:2023-09-26

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

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

有趣的小问题。我试图在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>

您可以为外部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
  });
});

这是一个工作样品。