1

This is my script I use to dynamically add/remove input text fields. I'm using the container properties so I can make multiple individual blocks for this input field.

$(function(){
    $('.container > a').click(function(e){
        e.preventDefault();
        var $this= $(this),
            prnt = $this.parent(),
            i = prnt.find('input').length;
        if($this.hasClass('add')){
            $('<div><input type="text" class="field" name="dynamic[]" value="' + i + '" /></div>').hide().fadeIn('slow').appendTo($('.inputs',prnt));
        }else if($this.hasClass('remove') && i > 1){
            prnt.find('input.field:last').remove();
        }else if($this.hasClass('reset') && i > 1){
            prnt.find('input.field:gt(0)').remove();
        }
    });
})

This is the html code I am using to build the input field:

<div class="container">
<a href="#" class="add">Add</a> | <a href="#" class="remove">Remove</a> | <a href="#" class="reset">reset</a>
    <div class="inputs">
        <input type="text" name="dynamic1" class="field"/>
    </div>
</div>

I need a PHP code to output all the fields from the input fields. If I add 3 input fields, I want the PHP code to output all of those input fields one after another.

I tried using the foreach code:

<?php
foreach($_POST['dynamic[]'] as $value) {
echo "$value <br />"; // change this to what you want to do with the data
}
?>

But I keep getting errors on the 2nd line (the foreach line)

How do I do this? Please help!

2 Answers 2

2

You should change

foreach($_POST['dynamic[]'] as $value) {

To

foreach($_POST['dynamic'] as $value) {

Thats is if you have HTML like this

<input type="text" name="dynamic[]" class="field"/>
<input type="text" name="dynamic[]" class="field"/>

But with your current HTML <input type="text" name="dynamic1" class="field"/> you can see that $_POST['dynamic'] is not a array you should just echo it like this

echo $_POST['dynamic1'] ;
Sign up to request clarification or add additional context in comments.

1 Comment

This works for the 2nd field, but it can't catch the data for the very first(initial) field! How do I get the data for the first field to show up as well? Please help!
1

instead of $_POST['dynamic[]' try $_POST['dynamic']

<?php
foreach($_POST['dynamic'] as $value) {
echo "$value <br />"; // change this to what you want to do with the data
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.