Reputation: 670
I have a form with cloned elements. The method of the form is POST
. When I dump the result of the POST only the final 'select' box value is shown because they are all the same. How can I change the name
tag to the cloned elements?
JSFiddle: https://jsfiddle.net/hLefegxz/
HTML
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select id="employees" name="employees" >
<option value="" selected disabled>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
JS for the Clone
$(function() {
$("#addMore").click(function(e) {
var newSelect = $("#select-employees").clone();
newSelect.val("123");
$("#employees-div").append(newSelect);
});
});
At the moment all fo the elements have the same name tag of employees. It obviously needs to be different to go into the $_POST
array
. How can I go about making them different? I was thinking maybe of incrementing and keeping a count? It Currently is like so:
Upvotes: 0
Views: 302
Reputation: 33870
Instead of using a name and increasing an integer on each "new employee", you could simply name your select to employees[]
. That will send every employee in an array format to your server, allowing you to use an easy loop.
Your code as another problem though. ID should be unique, so every time you clone your select
, you should change the ID.
Upvotes: 1
Reputation: 23379
Don't worry about changing the name, you can and should use an array for the name, but you should worry about the id, since ids must be unique and you are cloning elements without changing the id of the new element.
By adding the []
to the input name it will be sent to the server as an array, for example, if you're using PHP you can get them from $_GET['employees']
which will be an array you can loop thru.
$(function() {
$("#addMore").click(function(e) {
var newSelect = $('select[name="employees[]"]:first').clone();
$("#select-employees").append("<br>");
$("#select-employees").append(newSelect);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select name="employees[]" >
<option value="" selected>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
<button id=addMore>+ Employee</button>
Upvotes: 2