Nick Nick - 4 months ago 20
Javascript Question

jquery - add event listener to dynamically created button

I've tried multiple solutions but none worked and I don't understand why...

Basically, I have a button that appends a new form line into my page, with name, start and colour fields and a save button.

What I need to do is save the form fields on save click.

Here's the code I'm trying to use but it's not working:

var i = 0;
var addCounter = $("#addCounter");

addCounter.on("click", function () {
++i;
var body = $("body");
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);

var templateToAppend = '<li class="list-group-item">' +
'<div class="form-inline">' +
'<div class="form-group">' +
'<label for="counterName-' + i + '">Counter Name</label>' +
'<input type="text" id="counterName-' + i + '" placeholder="Counter name"/></div>' +
'<div class="form-group">' +
'<label for="counterStart-' + i + '">Starting from:</label>' +
'<input type="text" id="counterStart-' + i + '" placeholder="dd/mm/yy"/></div>' +
'<div class="form-group">' +
'<label for="counterColor-' + i + '">Counter Color:</label>' +
'<input id="counterColor-' + i + '" class="jscolor"></div>' +
'<button id="save-' + i + '" class="btn btn-primary">Save</button>' +
'<div id="status-' + i + '"></div></div></li>';
body.append(templateToAppend);
save.click(function () {
debugger;
console.log("clicked on save: ", save);
var localStorage = {
id: i,
counterName: name.value,
counterDate: date.value,
counterColor: color.value
};

console.log(localStorage);
});
});


the debugger never runs and I don't understand why.

Can you please help me understand why?

thanks a lot

Answer

Well that is because you have tried to create jquery object of element which is not there in DOM. You should append the element first and then get element by selector. Like this:

body.append(templateToAppend);
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);

also there is much cleaner way to attach event to dynamically added element. Have a look at Event Delegation

Comments