获取所有单选按钮和文本字段值
我的页面上有一个表单,位于类 .class-lesson 中。表单本身仅包含文本字段和单选按钮。我不知道每个表单中有多少个,因为它是由 PHP 动态生成的。表单中的每个新输入都被命名为 q1、q2、...qn。
我正在尝试获取所有值,无论是否已回答,并将其存储到 JavaScript 数组中。到目前为止,这是我的代码:
// get the value of each input field
var numQuestions = $(".class-lesson label").not(".csubmit").length;
// store each answer
for (var i = 0; i < numQuestions; i++) {
// store our variables
var tempAnswer = undefined;
var tempReference = $(":input[name=q"+(i+1)+"]");
// loop through each item
if ( tempReference.attr('type') == 'radio' ) tempAnswer = $(":input[name=q"+(i+1)+"]:checked").val();
else tempAnswer = tempReference.val();
// output / store the item
alert( tempAnswer );
}
我确信必须有一种更简单的方法来做到这一点,但我不知道。这就是我问的原因。如果我没有 :checked 那么它只会获取单选组的第一个值。
那么,我怎样才能提高效率呢?
I have a form on my page that is located in a class .class-lesson. The form itself only contains text field and radio buttons. I do not know how many of each are in the form since it is dynamically generated by PHP. Each new input in the form is named q1, q2, ... qn.
I am trying to get all the values, whether answered or not, and stored into a javascript array. This is my code so far:
// get the value of each input field
var numQuestions = $(".class-lesson label").not(".csubmit").length;
// store each answer
for (var i = 0; i < numQuestions; i++) {
// store our variables
var tempAnswer = undefined;
var tempReference = $(":input[name=q"+(i+1)+"]");
// loop through each item
if ( tempReference.attr('type') == 'radio' ) tempAnswer = $(":input[name=q"+(i+1)+"]:checked").val();
else tempAnswer = tempReference.val();
// output / store the item
alert( tempAnswer );
}
I am sure there has to be an easier way to do this but I don't know. This is why I am asking. If I don't have the :checked then it will just grab the first value of the radio group.
So, how can I make this more efficient?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要以序列化形式获取整个
例如,如果您通过 AJAX 提交,这将使您的代码非常简单,例如:
To get an entire
<form>
(or any set of inputs) in serialized form, as it would be if submitted to the server normally (without any JavaScript involved), use.serialize()
, like this:If you're submitting via AJAX for example this makes your code incredibly simple, for example: