Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add form element dynamically using javascript -- not submitting

Edit: I fixed the problem by just starting from scratch. Sorry to waste y'alls time. Please vote to close if you feel so inclined.

I'm having trouble getting the actual data in a form to submit when the input fields are added via javascript. The fields show up, and in the right place, but when I do a var_dump( fieldname) on the server side, nothing is showing up. Inspecting with Live HTTP headers tells me that the browser isn't trying to submit the dynamically added form fields.

Do I need to somehow "attach" my dynamically created form inputs to the form?

My code:

HTML

<form id="att_form" method="post" name="add_attachments" enctype="multipart/form-data" action="#">
<-- below input to prove form submits, just not the dyn added elements -->
<input name="data[one]" type="text" />
<div id="add_fields"></div>
<input type="submit" />
</form>

Javascript

function addFormField()
{
 var id = 1;
 var htm = "<p id='row" + id + "'><input type='text' size='20' name='txt[]' id='txt" + id + "' /></p>";
 $("#add_fields".append( htm );
}

When I submit the form, my input named data[one] shows up as a POSTd value, but those added with addFormField() do not. They show up, in the HTML, at the correct place, but don't POST. Do I need to append the element as a child to my form element to get it to submit?

I've seen Submit form input fields added with javascript which is where I got the idea of appending the data specifically to the form child, but that will require some restructuring of my CSS. So, I'm hoping that it's something simple I can do in the above code.

Thanks in advance!

edit: fixed the typos, but still not working. I've decided to use the library free JS method discussed in the SO link above, as that works fine. Thanks for the help though!

like image 823
Travis Leleu Avatar asked Sep 06 '09 17:09

Travis Leleu


2 Answers

there is 2 typos in your code: htm instead of html

and add_fields / add_files

like image 180
Olivvv Avatar answered Sep 25 '22 00:09

Olivvv


There were a lot of typos in your code. For example, you didn't close the selector tag for jquery.

You put $("#add_fields".append( htm );

Should have been $("#add_fields").append( htm );

Notice the missing parantheses.

But I believe your problem lies mainly in how you're trying to access the values through PHP. I just put your source in a test page and it all works if you access the values correctly.

<?php
foreach ($_REQUEST['txt'] as $printme) 
    echo $printme."<br/>";
?>

The above source works fine.

like image 41
MagikWorx Avatar answered Sep 26 '22 00:09

MagikWorx