Reputation: 1374
I'm having trouble to append multiple inputs. I am reading a list with items and values and want to submit them over Javascript (POST), but I can't figure out why this doesn't want to work. I tried in several ways, finally I came up with this, but it doensn't want to iterate over it and throw an error:
var form = document.createElement("form");
form.action = "submitform.php";
form.method = "post";
form.target = "_blank";
input = [];
var kvarray = document.getElementsByClassName('ua_mattext');
for (var i = 0; i < kvarray.length; i++) {
var fieldname = kvarray[i].id;
var fieldvalue = kvarray[i].value;
input[i] = "input_" + i;
document.createElement(input[i]);
input[i].type = "hidden";
input[i].name = fieldname;
input[i].value = fieldvalue;
form.appendChild(input[i]);
}
document.body.appendChild(form);
form.submit();
What am I doing wrong?
Upvotes: 0
Views: 1148
Reputation: 1374
I figured it out by myself. Firstly, I wasn't declaring the input
variable properly (Forgot the "var " at the beginning)
Secondly, I wasn't setting the document.createElement()
to the input.
Thirdly, I was naming the input input_1
,input_2
, which was invalid. There is only one, which is input
.
So, now it's working. Below is the corrected code:
var form = document.createElement("form");
form.action = "submitform.php";
form.method = "post";
form.target = "_blank";
var input = [];
var kvarray = document.getElementsByClassName('ua_mattext');
for (var i = 0; i < kvarray.length; i++) {
var fieldname = kvarray[i].id;
var fieldvalue = kvarray[i].value;
input[i] = "input_" + i;
input[i] = document.createElement("input");
input[i].type = "hidden";
input[i].name = fieldname;
input[i].value = fieldvalue;
form.appendChild(input[i]);
}
document.body.appendChild(form);
form.submit();
Upvotes: 1
Reputation: 691
When you say
input[i] = "input_" + i;
nothing about this line actually creates an input HTML element. Instead, you can do something like this
input[i] = <input type="hidden" name="${fieldname}" value="${fieldvalue}">
which would also have the added benefit of replacing the 3 lines following that one.
p.s: you should also declare input in the beginning by saying:
var input = []
p.p.s: You should check your assumptions as to what kvarray[i] is equal to. If you are doing kvarray[i].value in the subsequent line, I doubt that kvarray[i] is going to be a string, which is what you will need it to be in order to set the input's name attribute equal to it.
Upvotes: 0