如何在 Javascript 中以相同的方式获取文本框、文本区域和单选按钮的值?
我想要一个函数/代码,它将返回用户为其名称/id 传递给它的字段提交的值。 该字段是文本框、文本区域、单选还是选择并不重要。 例如,该字段可以是:
<input type='radio' name='a_21' value='test' id='a_21_0' />
<input type='radio' name='a_21' value='test2' id='a_21_1' />
或者
<textarea name="a_21" rows="30" cols="6"></textarea>
当我进行调用时:
function getVal('a_21');
它应该返回选定的值。
我怎样才能做到这一点? Will:
document.myForm.field.value
也适用于文本区域、下拉菜单和收音机吗?
I want a function/code which will return the value that the user submitted for the field whose name/id is passed on to it. It shouldn't matter whether the field is a textbox, textarea, radio, or select. For example, the field could be:
<input type='radio' name='a_21' value='test' id='a_21_0' />
<input type='radio' name='a_21' value='test2' id='a_21_1' />
Or
<textarea name="a_21" rows="30" cols="6"></textarea>
When I do the call:
function getVal('a_21');
It should return the selected value.
How can I do this? Will:
document.myForm.field.value
work for textareas, dropdowns and radios, too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是不同的小部件有不同的用途。 例如,具有多个可用选项、多个复选框甚至单个复选框(其值仅为“on”或“off”)的
但如果你想要一个单一的功能,你可以这样做:
The problem is different widgets have different purposes. For example, a
<select>
box with multiple selection available, multiple checkboxes, or even single checkboxes (whose value would be just "on" or "off") wouldn't have a single value, so it's ok for them to behave differently from other widgets.But if you want to have a single function, you could do something like:
使用 jQuery,您可以执行以下操作:
这将为您提供名称为 a_21 的字段的值,无论字段的类型是什么。
注意:不需要引号,但由于复选框数组,我已经开始尝试添加它们:
我认为安全比试图找出它不起作用的原因更好。
Using jQuery you can do:
This will give you the value on of the field with name a_21, so matter what the type of field.
Note: The quotes are not needed, but I've gotten in the the practice of adding them because of checkbox arrays:
I figure it's better to be safe than trying to figure out why it doesn't work.