0

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?

1 Answer 1

1

$(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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.