I'm trying to build a page with a few task lists. For this part, I want to use dynamic input fields. The form is being looped by a foreach, which looks to the number of users.
The problem now is that the tags (add, remove and reset) are not working except at the "first loop". And when I click on the on the first loop value, a field will be added at all the "loops", instead of only the first loop.
My PHP Code:
<?php
foreach (glob(/*user as file*/) as $filename) {
echo '
<div class="col-md-4 taskblock">
<img class="taskimage" src="../../../'.$filename.'"/>
<div class="name">User</div>
<div class="dynamic-form">
<a id="add">Add</a> | <a id="remove">Remove</a> | <a id="reset">Reset</a>
<form>
<div class="inputs">
<div><input name="dynamic[]" class="field" value="1" type="text"></div>
</div>
<input name="submit" class="submit" value="Submit" type="button">
</form>
</div>
</div>
';
}
?>
And my Script:
$(document).ready(function(){
var i = $('input').size() + 1;
$('#add').click(function() {
$('<div><input type="text" class="field" name="dynamic[]" value="' + i + '" /></div>').appendTo('.inputs');
i++;
});
$('#remove').click(function() {
if(i > 1) {
$('.field:last').remove();
i--;
}
});
$('#reset').click(function() {
while(i > 2) {
$('.field:last').remove();
i--;
}
});
// here's our click function for when the forms submitted
$('.submit').click(function(){
var answers = [];
$.each($('.field'), function() {
answers.push($(this).val());
});
if(answers.length == 0) {
answers = "none";
}
alert(answers);
return false;
});
});