admin管理员组文章数量:1335180
Is there any way to get type of input by having element name?
<form name="formQuestionnaire">
<input name="age" type="radio" id="age-1" />
<input name="age" type="radio" id="age-2" />
</form>
document.forms['formQuestionnaire'].elements['age']
return radio / checkbox / text
Is there any way to get type of input by having element name?
<form name="formQuestionnaire">
<input name="age" type="radio" id="age-1" />
<input name="age" type="radio" id="age-2" />
</form>
document.forms['formQuestionnaire'].elements['age']
return radio / checkbox / text
Share Improve this question edited Jul 7, 2021 at 8:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 7, 2013 at 15:16 FuryFury 4,7767 gold badges53 silver badges82 bronze badges 1-
1
Fire up the console in Chrome (press F12, click on console) and start typing things like
document.forms
and you'll see that you can explore the JavaScript DOM API. It's a pretty good way to learn. – Mikael Östberg Commented Mar 7, 2013 at 15:22
4 Answers
Reset to default 5Try
var x = document.forms['formQuestionnaire'].elements['age'];
x = x.length ? x[0] : x;
alert(x.type)
Demo: Fiddle
<input type="age" name="age" type="radio" />
...
var input = document.getElementById('age');
alert(input.type);
You can also get type
property:
var type = document.forms["formQuestionnaire"].elements["age"].type;
It is somewhat better than using getAttribute("type")
, since in case of non defined type
attribute (default is text
) the latter gives null
, while type
property returns text
, as it should be.
If you want more than one element. Fiddle
var x = document.forms['formQuestionnaire'].elements['age'];
for(var i=0;i< x.length;i++){
var u = x.length ? x[i] : x;
alert(u.type);
}
<form name="formQuestionnaire">
<input name="age" type="radio" id="age-1" />
<input name="age" type="checkbox" id="age-2" />
</form>
本文标签: javascriptHow to get input type by element nameStack Overflow
版权声明:本文标题:javascript - How to get input type by element name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742382060a2464288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论