You're having problems when attaching event handlers to dynamically added elements.
Also, you're using var
in a bit of your code that's resetting the variable counter
.
Check the comments in the code to spot what has been changed:
var counter = 1;
// Using delegation.
$(document).on("click", "#addButton", function () {
var datacounter = $('#TextBoxesGroup .textboxdiv_new:last-child').attr('data-id');
if (typeof (datacounter) != 'undefined') {
counter = parseInt(datacounter, 10) + 1;
} else {
counter = 1;
}
var quid = $(this).attr("data-id");
var datarole = $(this).attr("data-role");
if (counter > 10) {
alert("Only 10 textboxes allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr({
'id': 'TextBoxDiv' + counter,
'data-id': counter,
'class': 'textboxdiv_new'
});
if (datarole == "image") {
newTextBoxDiv.after().html('<div class="row"><div class="large-3 columns left button-mar-top-btm"><label class="tiny button radius multipleimg"><input type="file" name="ques_' + quid + '[]' + '" id="ques_' + quid + '[]' + '" value="" class="imgupload" data-id=' + counter + '>Upload Photo</label> </div><div class="large-7 left columns button-mar-top-btm"><input class="file-upload-input" type="text" id="filename' + counter + '"></div><div class="large-2 left columns button-mar-top-btm"><a href="#" class="button radius tiny alert removeField" >×</a></div></div>');
} else {
newTextBoxDiv.after('').html('<div class="row"><div class="large-10 columns"><input type="text" name="ques_' + quid + '[]' +
'" id="ques_' + quid + '[]' + '" value="" ></div><div class="large-2 columns left padding-top"><a href="#" class="button radius tiny alert removeField" >×</a></div>');
}
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
// Using delegation.
$(document).on("click", "a.removeField", function (event) {
event.preventDefault();
var newTextBoxDiv = $(document.createElement('div'));
var previd = $("input#addButton").attr("data-id");
var div = $(this).parent().parent().parent().remove();
var datacounter = $('#TextBoxesGroup .textboxdiv_new:last-child').attr('data-id');
if (typeof datacounter != 'undefined') {
// Removed the var because you don't want to reset counter.
counter = parseInt(datacounter, 10) + 1;
} else {
counter--;
}
if (counter <= 1) {
newTextBoxDiv.after().html('<input type="hidden" name="ques_' + previd + '" id="ques_' + previd + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
});
// Using delegation.
$(document).on('change', '.imgupload', function (e) {
var imgid = $(this).attr("id");
var filenames = [].slice.call(e.target.files).map(function (f) {
alert(f.name);
return f.name;
});
$('#filename' + $(this).attr("data-id")).val(filenames);
});
Demo