Providing some background story:
I am working on a edit button for my Content Management System, but I am bumping into a couple of problems now. I am finishing someone else his part (he built the CMS and I got assigned to his project and had to finish what he started basically) so there are certain parts I cannot edit or change.
Problem:
You can dynamically create input fields in the C.M.S, and then insert the data into Mysqli. Right now I am fetching the data successfully, but stumble upon the following problem: The input fields were created like this:
<input type="text" name="example[]" id="example[]"> //note the square brackets
and I cannot assign an incremented counter on these IDs, so I can assign my fetched data to the input fields. I am trying to loop through all of my data sets and then insert the first data it fetches to the first input field and the second data to the second input field and so on.
I was able to dynamically create the same amount of input fields, but the main problem is adding all the data to an individual input field. I keep on getting the last fetched data in all of my input fields.
What I have tried and how I tried inserting data1 in input field 1 and so on:
I know this sucks and I know it doesn't work and why it doesn't work, but I'll throw it in for you to get an idea.
for (var i = 0; i < response.length; i++) {
console.log(i);
$("#example\\[" + "\\]").each(function() { //already tried incrementing this part by using i as a counter, but it doesn't recognize the id when I use i as a counter.
$("#example\\[" + "\\]").val(response[i].exampleType);
});
}
What I am trying to achieve:
Example:
You have fetched your data in JSON format via ajax, your response parameter looks like this:
response = JSON.parse(response);
You have 2 rows in your database: row1 (from JSON.parse[0]) and row1 (from JSON.parse[1])
You have created the 2 input fields, dynamically (because you have response[0].example and response[1].example), but both input fields look like this:
<input type="text" name="example[]" id="example[]">
So that means you have dynamically created the following:
<input type="text" name="example[]" id="example[]">
<input type="text" name="example[]" id="example[]">
Now you have to insert row1 (from response[0].example) in the first input field and the other row1 (from response[1].example) into the second one.
How could such thing be achieved?
Thank you in advance for your time and effort
答案 0 :(得分:0)
your_json_array.forEach( function(obj) { //loop over your json array
var input = document.createElement("input"); //create an input
input.setAttribute("name", "yourname"); //custom it
input.setAttribute("value", obj.value); //custom it
//etc...
your_div.appendChild(input); //appends it where you want
});
Obj是响应的元素,并重视其中一个属性