简体   繁体   中英

JavaScript innerHTML trough form object

I have a form that I wish to use more than one time in the same page. Is a upload form working with a javascript. The issue is how to display feedback messages in each form, can't use document.getElementById because the id will be the same, so I changed the name of the form and access the form elements by document.forms. But, as you see in the example below...

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Label Changing: form approach</title>
<script>
function ini(){
    var form = document.forms["myForm"];
    document.getElementById("myLabel").innerHTML = "Usual Way Working";
    form.myLabel.innerHTML = "My Label Text";
}
</script>

</head>

<body onload="ini();">
<form name="myForm">
    <label name="myLabel" id="myLabel"></label>
</form>
</body>
</html>

the text "My Label Text" will not be displayed, it returns error: TypeError: 'undefined' is not an object (evaluating 'form.myLabel.innerHTML = "My Label Text"'), and only "Usual Way Working" remains. Why? How can I write inside label trough form way?

You can't access any element in a form that way, only controls.

Had you written

<form name="myForm">
    <input id="myInput">

then you could have accessed the input with form.myInput . But not labels or other elements.

You can write form.getElementById('myLabel') though.

Edit:
If you want to access any element by name rather than by ID, you can use the javascript querySelector function. For your original example that would be

var label = document.querySelector('form[name="myForm"] label[name="myLabel"]');
label.innerHTML = "My Label Text";

See jsFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM