JQuery submit (), change () and page refresh

I am trying to submit a form when I select an option. Without refreshing the page.

Example 1:

<form>
    <select>
      <option>Option 1</option>
      <option>Option 2</option>
    </select>
    <button type="submit">Submit</button>
</form>

.

$('select').change(function() {
        console.log('changed');
        this.form.submit(function (e) {
                alert('form submitted');
                e.preventDefault();
        });
});

Demo: https://jsfiddle.net/ty8Lrdm0/

Question: Why is formit still refreshing the page when submitted?

Example 2:

<form id="form">
    <select>
      <option>Option 1</option>
      <option>Option 2</option>
    </select>
    <button type="submit">Submit</button>
</form>

.

$('select').change(function() {
        console.log('changed');
        $('#form').submit(function (e) {
                alert('form submitted');
                e.preventDefault();
        });
});

Demo: https://jsfiddle.net/wsjLx1cs/2/

Question: Why does this example not work?

+4
source share
2 answers

I am trying to submit a form when I select an option. Without refreshing the page.

You should look for an AJAX method for a partial upgrade.

You can bind an event handler for the change and instead of trying to submit the form, execute an AJAX request, process the request on the server and pass the response to the client.

, , , .

, ,

$("#formid").submit();

.

jQuery ajax jQuery.ajax()

+1

this.form.submit(function (e) {
          alert('form submitted');
          e.preventDefault();
     });

this dom, jQuery, submit() , .

$('#form').submit(function (e) {
             alert('form submitted');
            e.preventDefault();
     });

, .

+2

Source: https://habr.com/ru/post/1621330/


All Articles