get all the elements of a particular form

2020-02-08 03:13发布

function getInputElements() {
    var inputs = document.getElementsByTagName("input");
}

The above code gets all the input elements on a page which has more than one form. How do I get the input elements of a particular form using plain JavaScript?

标签: javascript
12条回答
欢心
2楼-- · 2020-02-08 03:25
document.getElementById("someFormId").elements;

This collection will also contain <select>, <textarea> and <button> elements (among others), but you probably want that.

查看更多
Explosion°爆炸
3楼-- · 2020-02-08 03:28
document.forms["form_name"].getElementsByTagName("input");
查看更多
Deceive 欺骗
4楼-- · 2020-02-08 03:29

If you have a reference to any field in the form or an event then you don't need to explicitly look up the form since every form field has a form attribute that points to its parent form.

If you have an event then it will contain a target attribute which will point to the form field that triggered it, which means you can access the form via myEvent.target.form.

Here is an example without any form lookup code.

<html>
<body>
    <form name="frm">
        <input type="text" name="login"><br/>
        <input type="password" name="password"><br/>
        <button type="submit" onclick="doLogin()">Login</button>
    </form>
    <script>
        function doLogin(e) {
            e = e || window.event;
            e.preventDefault();
            var form = e.target.form;
            alert("user:" + form.login.value + " password:" + form.password.value);
        }
    </script>
</body>
</html>

If you have multiple forms on the page you still don't need to label them by name or id, because you'll always get the correct form instance via the event or via a reference to a field.

查看更多
在下西门庆
5楼-- · 2020-02-08 03:32

Try this to get all the form fields.

var fields = document['formName'].elements;
查看更多
不美不萌又怎样
6楼-- · 2020-02-08 03:33

How would you like to differentiate between forms? You can use different IDs, and then use this function:

function getInputElements(formId) {
    var form = document.getElementById(formId);
    if (form === null) {
        return null;
    }
    return form.getElementsByTagName('input');
}
查看更多
Rolldiameter
7楼-- · 2020-02-08 03:34

SIMPLE Form code

    <form id="myForm" name="myForm">
        <input type="text" name="User" value="Arsalan"/>
        <input type="password" name="pass" value="123"/>
        <input type="number" name="age" value="24"/>
        <input type="text" name="email" value="johndoe@test.com"/>
        <textarea name="message">Enter Your Message Her</textarea>

    </form>

Javascript Code

//Assign Form by Id to a Variabe
    var myForm = document.getElementById("myForm");
    //Extract Each Element Value
    for (var i = 0; i < myForm.elements.length; i++) {
    console.log(myForm.elements[i].value);
    }

JSFIDDLE : http://jsfiddle.net/rng0hpss/

查看更多
登录 后发表回答