Rakesh Singh
Rakesh Singh

Reputation: 25

Getting data from jquery loop in php

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.

Upvotes: 1

Views: 88

Answers (1)

JSowa
JSowa

Reputation: 10572

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>

Upvotes: 2

Related Questions