Trying my hand on dynamic form fields with itemz[].
I would like the form fields duplicate and have the select populate from the json object.
<!-- DYNAMIX ITEMS-->
<div class='container1'>
<tr>
<td>
<select id='itemz' name='itemz[]' class='itemz'> </select>
</td>
<td>
<input class='form-control' type='text' name='count[]' value=''>
<input class='form-control' type='hidden' name='weight[]' value='<?= $items['weight']; ?> '>
</td>
<!-- ADD MORE -->
<td>
<button class='add_form_field'>Add More</button>
</td>
</tr>
</div>
Here is the JS that is suppose to: 1) populate the drop down but it only populates the first box, I tried using a for each on the class but no luck.
2) Duplicates the dropdown, but instead of appending after it adds it before the first main div
<script>
// POPULATING THE DROP DOWN
var obj={
Prod:
<?php echo $products; ?>
};
for(var i=0;i<obj.Prod.length;i++)
{
var option=$('<option></option>').text(obj.Prod[i]['item']);
$( ".itemz" ).append(option);
}
// DUPLICATING THE DROP DOWNS
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".container1"); //Fields wrapper
var add_button = $(".add_form_field"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append("<tr><td><select id='itemz' name='itemz[]' class='itemz'></select></td> <td><input class='form-control' type='text' name='count[]' value=''><input class='form-control' type='hidden' name='weight[]' value=''> </td> <td><a href='#' class='remove_field'>Remove</a> </td></tr></div>"); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Here is my JSON object:
Prod:
[{"id":"1","item":"Piano","weight":"200"},{"id":"2","item":"Fridge","weight":"50"},{"id":"3","item":"Freezer","weight":"100"},{"id":"4","item":"Sofa","weight":"20"},{"id":"5","item":"Microwave","weight":"10"},{"id":"6","item":"Dining Table","weight":"40"},{"id":"7","item":"Coffee Table","weight":"20"}]
};