javascript - jquery - add event listener to dynamically created button -


i've tried multiple solutions none worked , don't understand why...

basically, have button appends new form line page, name, start , colour fields , save button.

what need save form fields on save click.

here's code i'm trying use it's not working:

var = 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-' + + '">counter name</label>' +         '<input type="text" id="countername-' + + '" placeholder="counter name"/></div>' +         '<div class="form-group">' +         '<label for="counterstart-' + + '">starting from:</label>' +         '<input type="text" id="counterstart-' + + '" placeholder="dd/mm/yy"/></div>' +         '<div class="form-group">' +         '<label for="countercolor-' + + '">counter color:</label>' +         '<input id="countercolor-' + + '" class="jscolor"></div>' +         '<button id="save-' + + '" class="btn btn-primary">save</button>' +         '<div id="status-' + + '"></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 , don't understand why.

can please me understand why?

thanks lot

well because have tried create jquery object of element not there in dom. should append element first , element selector. 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 cleaner way attach event dynamically added element. have @ event delegation


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

unity3d - Fatal error- Monodevelop-Unity failed to start -