从单选按钮组中获取所有选定值的最佳(和正确)方法是什么?
What is the best (and right) way to get all the selected values from groups of radio buttons
我正在学习HTML, JavaScript &NodeJs (I'm just getting started) .
我试图创建一个网站,其中用户将回答一些问题(与单选按钮),当用户点击提交按钮,答案将被发送到服务器)。
我正在创建这个javascript函数的问题:
<script type="text/javascript" >
var questionCounter = 0;
var questionId = 0;
function printQueue(question) {
questionId++;
questionCounter++;
var radioName="Q"+questionCounter;
var id = "Q" + questionCounter;
document.write("<p> <b> " + question + " </b> </p>");
document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
" onclick='"check(this.value)'" value='"5'">Best<br>");
document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
" onclick='"check(this.value)'" value='"4'">Very Good<br>");
document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
" onclick='"check(this.value)'" value='"3'">Good<br>");
document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
" onclick='"check(this.value)'" value='"2'">Not Good<br>");
document.write ("<input type='"radio'" id=" + id + " name=" + radioName +
" onclick='"check(this.value)'" value='"1'">Worst<br>");
}
</script>
,并以以下方式调用该函数:
<script type="text/javascript" >
printQueue("1. XXX1 ? ");
printQueue("2. XXX2 ? ");
printQueue("3. XXX3 ? ");
...
...
printQueue("N. XXXN ? ");
</script>
是否有一种方法可以遍历问题并获得每个问题所选答案的值?
我看:如何获取所选单选按钮的值
但是看起来很麻烦…
是否有这样的方法:
1. loop over the questions
1.1 for each Q getSelected().getvalue()
谢谢
这可能有帮助
HTML<form id="myForm">
<div class='Q'> <span>Q1</span>
<input type="radio" name="Q1" value="1" />1
<br />
<input type="radio" name="Q1" value="2" />2
<br />
<input type="radio" name="Q1" value="3" />3
<br />
</div>
<div class='Q'> <span>Q2</span>
<input type="radio" name="Q2" value="1" />1
<br />
<input type="radio" name="Q2" value="2" />2
<br />
<input type="radio" name="Q2" value="3" />3
<br />
</div>
<input type='button' value='Get Values' id='temp'>
</form>
JS
$('#temp').on('click', function () {
var Ans = [];
$('.Q').each(function (index, Obj) {
Ans.push({
"Name ": $(this).find('span').text(),
"Answer": $(this).find('input[type="radio"]:checked').val()
})
})
console.log(Ans)
});
演示相关文章:
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- javascript导入的最佳实践是什么
- 在ng重复循环中显示条件内容的最佳方式是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 在node.js中编写单元测试的最佳方式是什么
- 使用AJAX在Rails中提交动态表单的最佳方式是什么
- 使用Angular存储用户以前是否选中过复选框,然后再调用它的最佳方式是什么
- 列出没有 mysql 的元素的最佳方法是什么
- 在AngularJS中使用多个主题的最佳方式是什么
- 存储数据的最佳方式是什么,以便与jquery一起使用
- 在企业应用程序框架中包含js/css文件的最佳实践是什么
- 在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法是什么
- 用JavaScript随机给网页上的每个字母上色的最佳方式是什么
- 如果我返回表,检查 Ajax 调用是否为 200 OK的最佳方法是什么
- JavaScript - 创建可链接函数时的最佳方法是什么
- 在上下文菜单项单击上显示侧边栏/弹出窗口的最佳方法是什么
- 将JavaScript检测与MVC4显示模式集成的最佳方式是什么
- addEvent()传奇事件之后的当前最佳实践是什么