jengooo
jengooo

Reputation: 3

Submit dynamically created form with AJAX

I submit a static form with jQuery using an AJAX POST and it works just fine.

However, after the call, I replace the inside of my form with the result of the first AJAX call. After that, POSTing the form again won't work. But... why?

This is my form:

    <form>
      <div id="optionForm">
        Just some SELECT menus
      </div>        
    </form>

This is how I post the form and replace the inside of the form (with some SELECT menus):

<script>
    jQuery(document).ready(function() {
        $("select").change(function() {
            var data = $('form').serialize();
            $.post("/test/Update.do", data, function(data) {
                $("#optionForm").html(data);
            });
        });
    });
</script>

Upvotes: 0

Views: 814

Answers (1)

David Hedlund
David Hedlund

Reputation: 129832

It's not entirely clear from your question, but I'm guessing that the selects you are referring to are within the form?

$('select').change will only bind change listeners to the elements that are found at the time that $('select') is executed. When you replace the entire form, you destroy the old selects and create new ones, that do not have any listeners bound to them. Use delegated events instead:

$('#optionForm').on('change', 'select', function() {
    // post...
});

Upvotes: 1

Related Questions