0

I have a function in jQuery which adds to my jsp view a form in this way:

$("#mydiv").append("<form class=\"sendMessage\" id=\"" + item.message_id + "\">" +
                "<input type=\"submit\" value=\"Delete\" />" +
                "</form><br />");
});

I would like to maintain submitting this form action. So I have written this function:

$(".sendMessage").submit(function(event) {
    alert("sendMessage");
});

Unfortunately this isn't working. However when I have added simply my form directly to my jsp view, my submit function has worked.

<form class="sendMessage">
    <input type="submit" value="Delete" />
</form>

What am I doing wrong?

woyaru
  • 5,544
  • 13
  • 54
  • 92
  • Are you able to add the form ? Is form looking good and issue is with submit code ? – Riz Jul 18 '12 at 10:11
  • 1
    This question has already been answered here: http://stackoverflow.com/questions/203198/jquery-event-binding-on-dynamically-created-elements – fourcube Jul 18 '12 at 10:13

2 Answers2

2
$(document).on("submit","form.sendmessage",function(){alert("sendMessage");
});
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
0

Are you running any of this code on DOM ready i.e.

$(document).ready(function() {

// Handler for .ready() called. });

See http://api.jquery.com/ready/

??

and are you applying the submit binding on callback of the form being added to the markup via Jquery? because otherwise it might not exist yet.

Pricey
  • 5,799
  • 12
  • 60
  • 84