input tags with array
Recently I am doing a project in which I encountered a strange problem.
This is the progr开发者_StackOverflowam which previous programmer did MPAN:
<input name="mpan[]" id="mpan[]" value="" maxlength="2" size="2" >//this one to read
<input name="mpan[]" id="mpan[]" value="" maxlength="3" size="3">
<input name="mpan[]" id="mpan[]" value="" maxlength="3" size="3">
<input name="mpan[]" id="mpan[]" value="" maxlength="3" size="3">
<input name="mpan[]" id="mpan[]" value="" maxlength="3" size="3">//this one to read
I have to read it from a javascript what I did:
1) document.getElementByName("mpan").value
==> not reading script does not work
document.getElementByName("mpan[]").value
==> reading first one
3) document.getElementByName("mpan[0]").value
==> script does not work
4) document.getElementByName("mpan[3]").value
==> script does not work
5) document.getElementByName("mpan[]")[3].value
==> not working
Can anybody tell me how to read this from a javascript program?
In HTML the ID must be unique. So it is an error to use the same ID for more than one element.
Use different IDs for every element in the list. Supposedly you are parsing the POST (or GET) data with PHP, so that you can mantain the same name
(mpan[]) with no problem.
Furthermore, the IDs can be composed only by certain characters; from W3C HTML Recommendation:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (”-”), underscores (”_”), colons (”:”), and periods (”.”).
document.getElementsByTagName("input")[0].value
document.getElementsByTagName("input")[1].value
document.getElementsByTagName("input")[2].value
document.getElementsByTagName("input")[3].value
An id
is just a string, don't be fooled by the "[]" to assume this is an array, there's nothing to make the id
property's value (or any other) have a meaning in JavaScript.
<a id="throw('don't click me bro');" href="about:blank">This should be OK too</a>
Other than that id
s should be unique in the document.
This should work
function ReadLines() {
var x = document.getElementsByName("mpan[]");
alert(x[3].value);
}
One noticeable thing is id
has to be unique to each element so document.getElementById('mpan')
should not work.
The names of your fields can be same. So if you want to find elements based on names you can do:
document.getElementsByName('mpan[]')[0].value;
精彩评论