jquery 返回输入的类型
我有一个带有动态创建的表单元素的表单。
我需要获取每个元素的值,并发送 ajax 请求以确保数据正常(最简单的部分)。我可以很容易地获得每个元素的值,但问题出在单选按钮上。例如:
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
如果我执行类似...的操作,
$('.form_element').each(function(){
alert($(this).val());
});
它将打印所有单选按钮的值,无论是否选中。
我需要它只返回被检查的值。
那么,有没有办法从 jquery 返回输入元素的类型呢?
I have a form with dynamically created form elements.
I need to get the value of each element, and send an ajax request to make sure the data is ok (the easy part). I can get each elements value easy enough, but the problem comes in with radio buttons. For example:
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
if i do something like...
$('.form_element').each(function(){
alert($(this).val());
});
it will print the values of all of the radio buttons, regardless if it is checked or not.
I need it to only return the value of the one that is checked.
So, is there a way to return the type of an input element from jquery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
$('.form_element:checked')
仅获取选中的单选按钮的值。Use
$('.form_element:checked')
to get only the value of the checked radio buttons.除了 salgiza 提到的之外,您还可以使用 属性过滤器 来执行更通用的过滤,包括您的要求。
像: $('.form_element[checked=true]').each(function(){
警报($(this).val());
});
Besides salgiza has mentioned, you can also use Attribute filters to perform more generic filtering including your requirement.
Like: $('.form_element[checked=true]').each(function(){
alert($(this).val());
});
这就是你想要的。在循环内部,它留下了不需要的 jQuery 装箱。处理单选、复选框、文本、文本区域、选择一项。不考虑多选、文件……
This does what you want. Inside the loop it left away the unneeded jQuery boxing. Handles radio, checkbox, text, textarea, select-one. Doesn't account for select-multiple, file, ....
尝试:
try:
这个例子可能可以改进,但应该可以解决问题。
我使用以下 HTML 对其进行了测试,以便判断它是否正常工作(您的示例在每个单选选项上具有相同的值):
This example could probably be improved, but should do the trick.
I tested it using the following HTML, in order to tell if it was working (your example had the same value on each radio option):