Reputation: 61
I am trying to pass dynamically created form fields to a php script, and it's causing me a huge headache.
I've done this in the past many times, and I can't figure out what i'm doing wrong here.
Below is an example of what's going on:
A brief explanation: I have a form with a textarea, there is a button named "Add More", when clicked, a new textarea is generated via javascript. The textareas values are pushed into an array named "comments". When I try to loop through this array within my php script, it only gives me the first item, and none of the dynamically created ones.
HTML
<form action="" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<textarea name="comments[]"></textarea>
<a href="javascript: return null;" class="add-more">Add More</a>
</form>
JS
$(".add-more").click(function(){
var new_field = '<textarea name="comments[]"></textarea>';
$(this).before(new_field);
});
PHP - this is where the issue is, when I try to loop through the comments[] array, it only gives me the first one, and does not bring through any of the ones that were generated dynamically.
<?php
$comments = $_POST['comments'];
$commentString = "";
foreach($comments as $value) {
$commentString .= $value;
}
?>
So with the above, if I create 5 textareas using the "Add More" button, input some text into each one, and then submit the form, none of the dynamically created fields send through to the php.
Can anyone help?
Thanks!!
Upvotes: 1
Views: 5852
Reputation: 61
This has been resolved.
The issue was being caused by an unclosed form above the one I was having the issues with.
Thanks for the replies everyone!
Upvotes: 1
Reputation: 7847
<form action="" method="post" />
should be:
<form action="" method="post">
Upvotes: 4
Reputation: 1
Also, the class name in your JS didn't match the class name in your HTML.
Here it is all together and working:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<textarea name="comments[]"></textarea>
<a href="javascript: return null;" class="add-more">Add More</a>
<input type="submit" />
</form>
<script>
$(".add-more").click(function(){
var new_field = '<textarea name="comments[]"></textarea>';
$(this).before(new_field);
});
</script>
<?php
$comments = $_POST['comments'];
$commentString = "";
foreach($comments as $value) {
$commentString .= $value;
}
echo $commentString;
?>
</body>
</html>
Upvotes: 0
Reputation: 352
The other answer is correct, but you also will need to close the form as well. Your code was missing the closing ">" as well.
<form action="" method="post" >
<textarea name="comments[]"></textarea>
<a href="javascript: return null;" class="add-more">Add More</a>
</form>
Upvotes: 0