简体   繁体   中英

Why is on('submit') function is never called when clicking on input type submit?

All worked well yesterday but today I did smth stupid and onsubmit jquery callback crashed.

First off, jQuery is on classpath and other callbacks work. But I cannot register callback on submit event with jQuery. My callback:

var $form = $('#hostelSearchForm');
    $form.on('submit', function(e) {
            //console.log($('#hostelSearchFormButton').attr('id'));
            hostelSearchJson = collectHostelSearchFormData($form);
            console.log(JSON.stringify(hostelSearchJson));
            //do ajax search
            hostelSearch(hostelSearchJson);
            //serializing is bad because of checkboxes value as on and off
            // console.log(JSON.stringify($form.serialize()));
            e.preventDefault();
            return false;
        });

And this form with corresponding input of type submit:

<form:form id="hostelSearchForm" modelAttribute="hs" method="POST"
                cssClass="mainForm">
.........................
<div>
                    <fmt:message key="searchButtonLabel" var="searchButtonLabel" />
                    <input id="hostelSearchFormButton" type="submit" class="btn btn-primary"
                            style="font: bold 18px Tahoma, serif; padding: 15px"
                            value="${searchButtonLabel}" />
                            &nbsp;&nbsp;&nbsp;&nbsp;
                        <button type="reset" class="btn">
                            <fmt:message key="cancel" />
                        </button>
                </div>
</form:form>

When I click hostelSearchFormButton it redirects me to new page and gives

415 Unsupported Media Type. 

In chrome I see that it makes post request with text/html as media type.

Even when I attached callback on hostelSearchFormButton it is not fired. But all other callbacks on this page are working well.

It's so stupid error and I cannot understand what is wrong?

Very good question,

this happens 'cos submit in first instance use HTML after javascritp, so when you click it, per default html send form data, to avoid this effect add in your form tag onsubmit="return false" like this:

<form action="my.php" onsubmit="return false">

when you finish what you wanna do in jquery, you can send data with

$('form').submit();

au revoir

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