开发者

Finding a form element's type after finding it by name or id

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

Example:

<input type="text" name="my_text_input" id="my_text_input"/>
<script>var element = document.getElementById('my_text_inp开发者_JAVA技巧ut'); // now how to get the element type?</script>

I'm not looking for alternatives, this is exactly what I want to do. I'm making a sort of screen scraper that needs to collect this information.


The type property will give you this...

document.getElementById('my_text_input').type;

However, you have also tagged the question with jQuery, so you could use...

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

jsFiddle.


$('#form_id input').each(function() {
console.log($(this).attr('type'));
});


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

Similary you can get any propery....class,title or any

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


try this :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜