javascript - calling jquery function from a link after adding link using jquery -
i trying call jquery function after add using jquery. here code (this in document.ready):
$("#addrow").on("click",function() { alert("made it"); //$('#moduletable tr:last').after('<tr class="child"'+table_length+'><td>info</td><td></td><td></td></tr>'); table_length += 1; }); $("input[name='module_type']").change(function(){ var content = ""; //content += '<a href="javascript:void(0);" id="addrow">add row</a>'; content += '<br><br>'; content += '<table id="moduletable" style="width:100%">'; content += '<tbody>'; content += '<tr>'; content += '<td align="center">question</td><td align="center">header</td><td align="center">content</td>'; content += '</tr>'; content += '</tbody>'; content += '</table>'; $("#content").html(content); });
the problem
content += '<a href="javascript:void(0);" id="addrow">add row</a>';
if write html page when loads function gets called. if add link after page loads, doesn't.
i'm not jquery expert, believe you're not assigning function elements.
from jquery documentation:
the .on() method attaches event handlers selected set of elements in jquery object
when call $("#addrow").on( ... )
there no elements matching query #addrow
, meaning "currently selected set of elements" empty, i.e. $("#addrow").length == 0
the solution either set event after element created or assign event parent fires when specified elements targeted. creating elements through html prior not applicable.
the latter (as mentioned user1663189) use .delegate()
instead, wich "attach handler [...] elements match selector, or in future". rayon dabre pointed out can use optional parameter .on(event [, selector])
and assign listener parent element same result.
Comments
Post a Comment