Search for the type of a form element after finding it by name or identifier

Probably a dumb question, but is there a way in JavaScript to find out the type of form element (text, checkbox, etc.) from the form element after finding it by name or identifier? Either in plain old JavaScript, or using syntax or jQuery-style methods would be ideal.

Example:

<input type="text" name="my_text_input" id="my_text_input"/>
<script>var element = document.getElementById('my_text_input'); // now how to get the element type?</script>

I'm not looking for alternatives, this is exactly what I want to do. I am pretending to be a screen scraper that should collect this information.

+3
source share
4 answers

The property typewill give you this ...

document.getElementById('my_text_input').type;

However, you also noted the question with jQuery so you can use ...

$('#my_text_input').attr('type');

jsFiddle .

+5
source
$('#form_id input').each(function() {
console.log($(this).attr('type'));
});
0
source
$('#my_text_input').attr('type');

.... ,

$('#my_text_input').attr('class');//

0

:

<!DOCTYPE html>
<html>
<body>

<script language="JavaScript" type="text/javascript"> 

function submit_form()
{
    var len = document.form1.elements.length;

    for(var i = 0 ; i< len;i++){
        if(document.form1.elements[i].type == "text")
            alert(document.form1.elements[i].value);
    }
}

</script>
<form  name="form1" onsubmit="submit_form();">
First name: <input type="text" name="FirstName" value="Mickey"><br>
First name: <input type="textarea" name="FirstName" value="Mickey"><br>
Second name: <input type="text" name="SecondName" value="Mickey"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>
<input type="submit" value="Submit">
</form>


</body>
</html>
0

All Articles