MrUser
MrUser

Reputation: 1237

Dynamic form elements added with Javascript/jQuery not being POSTed

I read many discussions about this subject. (including " Submit form input fields added with javascript " which finally got me on the right track.) However, none of them completely answered the question or fixed my problem, so I figured I would make a post of my solution.

I was trying to dynamically add extra text input fields to a form using jQuery with this code I found:

jQuery("#form_table").append(
'<tr><th>'+
'<label><b>Date: </b></label></th><td>'+
'<input type="text" id="extra_date'+counter+'" />'+
'<label><b>Time: </b></label>'+
'<input type="text" id="extra_time'+counter+'" /></td></tr>');

The text fields were added to the table in the form and when I investigated the DOM using firebug, they were there. However, when I submitted the form, the variables extra_date1/extra_time1 were not in the $_POST array. I found that this code was not adding the elements to the FORM itself. The above post pointed me in the right direction using JS, not jQuery. I tried posting to the form as they mentioned in that post, but that didn't work. Eventually, this code worked for me:

var theForm = document.getElementById("form_table");
var newOption = document.createElement("input");
newOption.name = "extra_date"+counter;
newOption.type = "text";
theForm.appendChild(newOption);
var newOption = document.createElement("input");
newOption.name = "extra_time"+counter;
newOption.type = "text";
theForm.appendChild(newOption);

The form_table element is the table tag inside the form tag. Unlike the code from the post above, I found that you couldn't just append it to the form element itself. It has to be an element in the form.

I know this seems really simple, but it looked like a lot of people online were having this same problem, so I hope this will be a concise answer for someone who is pulling their hair out like I was.

Upvotes: 1

Views: 1577

Answers (1)

user1219892
user1219892

Reputation:

Your code has only id="" doesn't have name="" you should have name="" this is what gets posted . .

use this code instead:

jQuery("#form_table").append(
'<tr><th>'+
'<label><b>Date: </b></label></th><td>'+
'<input type="text" name="extra_date'+counter+'" />'+
'<label><b>Time: </b></label>'+
'<input type="text" name="extra_time'+counter+'" /></td></tr>');

Upvotes: 1

Related Questions