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
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>

本文标签: javascriptHow to get input type by element nameStack Overflow