1

I have a form in which I am adding new rows in one of the div through jquery

<div class="packs">
  <div>
     <input type="text" placeholder="Enter Name" name="pname" id="pname" value="Test" />
     <img class="add-icon" src="media/icon/add.png" height="30" width="30">
  </div>
</div>

In jquery, I am doing this:

$(document).ready(function(){      
  $(".packs").on('click', '.add-icon', function () {
     $(".packs").append('<div><input type="text" placeholder="Enter Name" name="pname" id="pname" value="Test" /><img class="add-icon" src="media/icon/add.png" height="30" width="30"></div>');
  });
});

What I need is to get array of all the elements which I have added. $_POST['pname'] is returning only last entered element.

Can someone suggest what to do here.

2
  • You must ask more precise question. Array of what? You need to store this array in JS or PHP? Commented May 8, 2020 at 11:15
  • All rows with id="pname". This data will be stored in database through php. This is not an ajax query, and I need data of all the rows together when I submit the form. Commented May 8, 2020 at 11:20

1 Answer 1

2

If you want to store in database I assume that you submit this form at the end of filling in.

Then you should add indices to the individual rows. You will get array under variable $_POST['pname'].

$(document).ready(function(){      
    let id_no = 0;
    $(".packs").on('click', '.add-icon', function () {
        id_no += 1;
        $(".packs").append('<div><input type="text" placeholder="Enter Name" name="pname[' + id_no + ']" class="pname" value="Test" /><img class="add-icon" src="media/icon/add.png" height="30" width="30"></div>');
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="packs">
    <div>
        <input type="text" placeholder="Enter Name" name="pname[0]" id="pname" value="Test" />
        <img class="add-icon" src="media/icon/add.png" height="30" width="30">
    </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.