获取div中的所有输入以进行ajax请求
我正在尝试获取所有输入文本框、单选按钮组、复选框等。我在获取选定的单选按钮和复选框值时遇到问题,我无法弄清楚。
我可以获得文本框,但似乎无法在正确的位置获得“选定”。目前它只是获取单选/复选框的第一个值而不是选定的值。
$('#form_1 input').each(function(key)
formData += '&'+$('#'+this.id).attr('name')+'='+$('#'+this.id).val();
});
谢谢
已编辑
$('#form_1 input').each(function(key, value) {
if ((this.type === "radio" || this.type === "checkbox") && this.checked === true) {
val = this.value;
} else {
val = this.value;
}
alert($('#'+this.id).attr('name') + ' = ' + val);
formData += '&'+$('#'+this.id).attr('name')+'='+val;
});
好的,现在我得到了收音机等的所有价值,所以我又近了一步。现在只需要获取所选无线电的值即可。
谢谢
I am trying to get all input textboxes, radio groups, checkboxes etc. I am having trouble getting the selected radio and checkboxs values, I cant figure it out.
I can get the text boxes but can't seem to get the "selected" in the right place. At the moment it just gets the first value for radio/checkboxes not the selected value.
$('#form_1 input').each(function(key)
formData += '&'+$('#'+this.id).attr('name')+'='+$('#'+this.id).val();
});
Thanks
EDITED
$('#form_1 input').each(function(key, value) {
if ((this.type === "radio" || this.type === "checkbox") && this.checked === true) {
val = this.value;
} else {
val = this.value;
}
alert($('#'+this.id).attr('name') + ' = ' + val);
formData += '&'+$('#'+this.id).attr('name')+'='+val;
});
Ok now I get every value for radios etc so I am a step closer. Just need to get the values of selected radios now.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
serialize()
[docs] 方法。它将负责为您获取所选元素的值。
来自文档:
Just use the
serialize()
[docs] method.It will take care of getting the values of the selected elements for you.
From the docs:
对于单选按钮和复选框,您关心的是选中的属性。
更新
您编写了
(this.type === "radio" || (this.type === "checkbox" && this.checked === true))
你的意思是
((this.type === "radio" || this.type === "checkbox") && this.checked === true)
你需要这些括号在正确的地方。
进一步编辑
逻辑有点混乱。
基本上就是你想要的。
这意味着如果它是一个未选中的单选/复选框,则您什么也不做。
For radios and check boxes you care about the checked attribute.
Update
You wrote
(this.type === "radio" || (this.type === "checkbox" && this.checked === true))
You meant
((this.type === "radio" || this.type === "checkbox") && this.checked === true)
You need those brackets in the right place.
Further edit
The logic was a bit broken.
Basically what you want.
This means if its a non-checked radio/checkbox you do nothing.
这并没有直接回答您的问题,但看起来您正在尝试实现已经可用的东西 - 您可能想查看
serialize()
- 将其用作var formData = $('#form_1').serialize()
This doesn't answer your question directly but it looks like you're trying achieve something that's already available - you might want to check out
serialize()
- use it asvar formData = $('#form_1').serialize()