简体   繁体   中英

Submit form via ajax doesn't work on dropdown index change

Here is the wired situation. This is my form:

using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { @class = "myForm" }))
{
    <select name="statusId" onchange="this.form.submit();" class="selectField">
            <option value="-1">-- Pick Item --</option>
            <option value="1">Item XYZ</option>
    </select>
    <button>SUBMIT</button>
}

And I have this simple ajax call:

    $(".myForm").on("submit", function (event) {                
        event.preventDefault();                
        var url = $(this).attr("action");
        var formData = $(this).serialize();
        $.ajax({
            url: url,
            type: "POST",
            data: formData,
            dataType: "json",
            success: function (response) {
                alert(response);
            }
        });
    });

When I click on button it works fine (use ajax).
But I don't need ajax on button I need it on select index change.
When I change selected index it make post to action method but not via ajax.
What I miss here?
What is the difference?

Here is all the code you need for all that to work:

$(function() {
    $('button').on('click', function() {
        $('.myForm')[0].submit();
    });
    $('select[name="statusId"]').on('change',function() {
        $('.myForm').triggerHandler( 'submit' );
    });
    $(".myForm").on("submit", function() {                                
        var url = $(this).attr("action");
        var formData = $(this).serialize();
        $.ajax({
            url: url,
            type: "POST",
            data: formData,
            dataType: "json",
            success: function (response) {
                alert(response);
            }
        });
    });
});

You do not need inline JS in the select element:

<select name="statusId" class="selectField">

Note: You may want to give the button a more specific selector if there are other buttons on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM