richj
richj

Reputation: 461

jQuery - How to dynamically assign form object

I'm trying to have a single function for submitting forms on various modals on my site. The problem I am having is when trying to serialize the form I get the error 'form.serialize() is not a function". I believe I've narrowed it down to how I am assigning the form variable.

The Submit Button:

<button id="modalSave" class="btn btn-primary" data-url="/Donors/save" data-form="#DonorAddForm" type="button">Submit</button>

The Submit Function:

$(".container").on("click", "#modalSave", function() {
    var form = $(this).data('form');

    $.ajax({
        url: $(this).data('url')
        dataType: "html",
        data: form.serialize(),
        beforeSend: function() {
            $("#loading").fadeIn();
        },
        success: function(data, textStatus) {
            $("#modalStatus").html(data);
        },
        complete: function() {
            $("#loading").fadeOut();
        }
    });
});

If I change the line:

var form = $(this).data('form');

to:

var form = $('#DonorAddForm');

then the 'form' variable is assigned the form object, otherwise it is simply assigned as a string.

How can I assign the object to the 'form' variable instead of a string?

Upvotes: 0

Views: 60

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

$(this).data('form') doesn't return a DOM element - it returns the value of the data-form attribute, which in this case is the string #DonorAddForm. To retrieve the respective DOM element, use jQuery to grab the element by id:

var formData = $(this).data('form'); // "#DonorAddForm"
var form = $(formData); // DOM element with id="#DonorAddForm"

Upvotes: 1

Related Questions