vendredi 27 février 2015

attach an event to dynamically created forms

I have a simple web page that grabs a list of items from the database and presents them as forms that can be updated by the user. I am trying to grab the submit event and update the form using ajax. I can't figure out how to make my jQuery function aware of my newly created forms though. Here is my HTML:



<body>
<ul class="flight-list>
<li>
<form>form stuff</form>
</li>
<li>
<form>form stuff</form>
</li>
<li>
<form>form stuff</form>
</li>
<li>
<form>form stuff</form>
</li>
... etc
</ul>
<form>Form to add new records</form>


The form to create new records works fine exactly as expected, and is not dynamically created.


Here is the jQuery:


Create form:



$('form').on('submit', function(event){
event.preventDefault();
var form = $(this);
var flightData = form.serialize();

$.ajax({
type: 'POST', url: '/flights', data: flightData
}).done(function(data){
var i = data.length - 1;
var flight = data[i];
addFlightsForm([flight]);
form.trigger('reset');
});
});


Update form:



$('form').on('submit', function(event){
event.preventDefault();
var form = $(this);
var flightData = form.serialize();

$.ajax({
type: 'PUT', url: '/flights/27', data: flightData
}).done(function(data){
// update specific form with new value
})
})


I know there is some way to attach an event to a dynamically created element, but I can't figure out how to do it.


Aucun commentaire:

Enregistrer un commentaire