繁体   English   中英

如何检查(动态)检查了哪个单选按钮?

[英]how to check which radio button (dynamically) is checked?

我正在创建一个在线考试门户,下面是向候选人显示问题的代码。 我不知道如何处理候选人点击的答案

$("input[name='hello']").click(function(){
    alert("you clicked on");
});

动态为100个问题创建单选按钮,每个问题4个

尝试这个 -

 $('input[data-type=choice]').change(function() { var Question = $(this).attr('name'); var Checked = $(this).attr('value'); console.log('Selected Choice for ' + Question + ' is ' + Checked); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" value="Log all Answers" onclick="logAllAnswers()"> <input type="button" value="Clear Log" onclick="console.clear();"> <hr> <form> <fieldset> <legend>1. Select the answer for the first question.</legend> <input type="radio" data-type="choice" name="Q1" value="1">Option 1 <br> <input type="radio" data-type="choice" name="Q1" value="2">Option 2 <br> <input type="radio" data-type="choice" name="Q1" value="3">Option 3 <br> <input type="radio" data-type="choice" name="Q1" value="4">Option 4 </fieldset> <fieldset> <legend>2. Select the answer for the second question.</legend> <input type="radio" data-type="choice" name="Q2" value="1">Option 1 <br> <input type="radio" data-type="choice" name="Q2" value="2">Option 2 <br> <input type="radio" data-type="choice" name="Q2" value="3">Option 3 <br> <input type="radio" data-type="choice" name="Q2" value="4">Option 4 </fieldset> <fieldset> <legend>3. Select the answer for the third question.</legend> <input type="radio" data-type="choice" name="Q3" value="1">Option 1 <br> <input type="radio" data-type="choice" name="Q3" value="2">Option 2 <br> <input type="radio" data-type="choice" name="Q3" value="3">Option 3 <br> <input type="radio" data-type="choice" name="Q3" value="4">Option 4 </fieldset> </form> <script> function logAllAnswers() { $('input[data-type=choice]:checked').each(function() { var Question = $(this).attr('name'); var Checked = $(this).attr('value'); console.log('Selected Choice for ' + Question + ' is ' + Checked); }); } </script> 

考虑每个选项的值

然后使用它来了解单击了哪个:

$("input[name='hello']:checked").val();

您可以这样重写代码:

$("input[name='hello']").click(function(){
   var v=$("input[name='hello']:checked").val();
   alert("you clicked on"+v);
});

假设您每隔4个框就有一个带有questionWrapper类的div,则可以执行以下操作:

var collection = $(".questionWrapper");
$.each(collection, function(i, $questionWrapper, function(){
    //Do this for all the questions
    //Find the checked input (maybe use classes here...) and get its value
    var clickedAnswer = $($questionWrapper).find("input:checked").val();
    //Do something with the clicked var, maybe push it to an array and then compare the array to the solution
});

暂无
暂无

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

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