Multiple Elements in a Form to JavaScript
I have a multiple text boxes
in a form in a HTML page. I want to read the values of the element to an array in the JavaScript. I will set the name
and ID
of 开发者_运维百科each element to name[]
and ID[]
respectively. How can I read the values of the elements to an array
in the JavaScript for further operations.
Also, On Update of each element, I want to add the value of the element in the respective positions in the array, ex: the first element in the form in location 0, the second in location 1 ... etc
First, don't set the id of the element to "ID[]". The id is a NAME token and:
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 (".").
Also, an id must be unique. So while you can have multiple elements with the same name, they cannot share an id.
Then, you can get a NodeList (which is almost certainly sufficiently array-like for your purposes) of all the form controls, in a given form, which share a name via:
document.forms.id_of_form.elements.name_of_inputs
Since the name includes the characters '[' and ']', which have special meaning in JavaScript, you'll have to use square bracket notation instead of dot notation for the last bit.
document.forms.id_of_form.elements['name_of_inputs[]']
I would use getElementsByTagName
.
And heed David Dorward's comments about use of the ID attribute.
Here is an example program that does what you want. Hope this helps.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form name="frm" id="frm">
<label>Name1: </label><input type="text" name="text1" id="text1">
<br>
<label>Name2: </label><input type="text" name="text2" id="text2">
<br>
<label>Name3: </label><input type="text" name="text3" id="text3">
<br>
<label>Name4: </label><input type="text" name="text4" id="text4">
<br>
<label>Name5: </label><input type="text" name="text5" id="text5">
<br>
<button id="b1">Click 1</button>
</form>
<script type="text/javascript">
var b1 = document.getElementById("b1");
if(b1){
b1.onclick = function(){
var frm = document.getElementById("frm"),
vals = [];
if(frm){
var textEls = frm.getElementsByTagName("input");
for(var i =0, l = textEls.length; i < l; i++){
var textEl = textEls[i];
if(textEl && textEl.type.toLowerCase() === "text" ){
vals.push(textEl.value);
}
}
}
alert("Resultant Array: " + vals);
};
}
</script>
</body>
</html>
精彩评论