javascript - How to get input type by element name - Stack Overflow

Is there any way to get type of input by having element name?<form name="formQuestionnaire&quo

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
Add a ment  | 

4 Answers 4

Reset to default 5

Try

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742382060a4433314.html

相关推荐

  • javascript - How to get input type by element name - Stack Overflow

    Is there any way to get type of input by having element name?<form name="formQuestionnaire&quo

    22小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信