Arel
Arel

Reputation: 3938

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.

Upvotes: 1

Views: 70

Answers (3)

Sasanka Panguluri
Sasanka Panguluri

Reputation: 3128

Take a look at LiveQuery

LiveQuery

This is one getaway-package that will attach event handlers to events happening with elements regardless of whether they're dynamically generated or already present.

var $mylist = $('#mylist');
$mylist.livequery(
    '.element', // the selector to match against
    function(elem) { // a matched function
        // this = elem = the li element just added to the DOM
    }, function(elem) { // an unmatched/expire function
        // this = elem = the li element just removed from the DOM
    });

Upvotes: 0

jfive
jfive

Reputation: 56

I don't have high enough reputation to add a comment to yours of

"Can you give me an example with my jQuery? $('document').on('submit', 'form', function(event){alert("hello);}); and nothing is happening." but,

make sure you have the code surrounded by

$(document).ready(function () {
//your code
});

Upvotes: 1

Lesha Ogonkov
Lesha Ogonkov

Reputation: 1238

Attach listener to document

$(document).on('submit', 'form', yourHandler);

Upvotes: 2

Related Questions