0

These form is dynamically added to the document:

<form action="" method="post">
   name:<input type="text" name="name" /> <br/>
   <p><input type="submit" /></p>
</form>

and the jquery/js function doesnt work for it.

$(function() {
    $('form').on( "submit", function(e) {    
        e.preventDefault(); // Stop normal submission
        alert("submit");

If i add the form direct to the document instead of dynamically then it works. Whats wrong? Any ideas?

Luk4s
  • 37
  • 9
  • Possible Duplicate http://stackoverflow.com/questions/11296530/jquery-onclick-vs-click-and-delegateclick and http://stackoverflow.com/questions/14679432/jquery-event-delegation and http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements – Mohamed-Yousef May 16 '16 at 21:35
  • Thanks, it works now. – Luk4s May 16 '16 at 21:43

1 Answers1

0

Changed

$(function() {
        $('form').on( "submit", function(e) {    

to

$(document).on( "submit", 'form', function(e) {   
Luk4s
  • 37
  • 9
  • I would recommend looking at a better target element personally.. This will technically run that function for every single form element within the document. It might not be a problem in your case, but always best to follow best practice where possible. See a Q just like this I answered earlier: http://stackoverflow.com/questions/37257890/jquery-click-on-now-triggering-close-using-load/37257960?noredirect=1#comment62043525_37257960 – Shakespeare May 16 '16 at 21:59
  • Yes i want to add more forms dynamically and i need to know from which table they are, i could write the tablename as id of the form. But i dont like to write multiple times the same js-function. Is it possible to get the id of the form which is actually submitted without catching it over theyr id at function-call? – Luk4s May 16 '16 at 22:17
  • If they are all in tables, could you not do `$('table').on( "submit", 'form', function(e) { `? Then you should be able to use `e.target.id` for the id of the form. Listening on tables is at least an improvement on using the document. – Shakespeare May 17 '16 at 07:59
  • Good idea but doesn't work for me and i don't know why. I have a table and if you click on a row there is da slidedown under the row in which i add a form with a table inside. So thats my "edit" of each row. I need to know from chich table it is to add multiple tables on one page. If i do $('table').on... or $('form').on... or $('td').on... nothing happens. – Luk4s May 17 '16 at 14:40
  • var contentPanelId = jQuery(this).attr("id"); alert(contentPanelId); this give me the id of the form – Luk4s May 17 '16 at 14:53
  • What point in the code are you getting that ID? When it is created? – Shakespeare May 17 '16 at 16:06
  • Dynamically if you click on an row in a table I echo '
    '; under the selected row.
    – Luk4s May 17 '16 at 17:13