This is the code in append input box in java script,i don't get there values in the inputbox
<script type="text/javascript">
function addIn开发者_StackOverflow中文版put()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" name=\"box[]\" id=\"box[]\"/>";
i++;
}
function getdata()
{
}
</script>
<input type="button" onmousedown="addInput();" value="add" />
<input type="button" value="getvalues" onclick="getdata()" />
<div id="inputs"></div>
What you are doing should work, but another way of doing it is (slightly more efficient):
function addInput() {
var input = createTextInput({
"type": "text",
"name": "box[0]",
"id":"box[]",
"value": "This is a value"
});
document.getElementById("inputs").appendChild(input);
}
// warning: just to be safe, don't pass any option object that extends any
// browser's native object or built in objects.
function createTextInput(options) {
var i = document.createElement("input");
for(key in options) {
i[key] = options[key];
}
return i
}
function getValues() {
var div = document.getElementById("inputs");
var values = [];
var textBoxes = div.getElementsByTagName("input");
for(var i = 0, len = textBoxes.length; i < len; i++) {
var box = textBoxes[i];
if(box && box.name === "box[]") {values.push(box.value);}
}
return values;
}
There are other ways of doing it, e.g. using jQuery, its much simpler and less verbose, but this is just the plain 'ol js way
The code itself should work. Try this: copy addInput from the function declaration to the callin the onmousedown.
For some reason the call from mousedown is not recognized. My JS-engine tells me, that addInput (like written in mousedown) was not found.
To get the values of the input fields, assign a name to the input fields and you can access it through form. When there are multiple fields of the same name, the fields will be returned as an array:
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" name=\"userNames\"/>";
}
function getdata()
{
var form = document.forms['myForm'];
//To handle single/multiple input elements
var names = !form.userNames[0] ? [form.userNames] : form.userNames;
var nameValues = [];
for(var index = 0; index < names.length; index++) {
nameValues[index] = names[index].value;
}
return nameValues;
}
</script>
<form name="myForm">
<input type="button" onmousedown="addInput();" value="add" />
<input type="button" value="getvalues" onclick="alert(getdata())" />
<div id="inputs"></div>
</form>
精彩评论