submitting a form without hitting the update or submit button

I have a form and i need to submit the form as soon as some change has been made to one of the fields in the form without having the user to click update or submit button.

I am familiar with AJAX and I can get the form to submit via AJAX using a button, but i now need to change this to submiting a form as soon as the user types something in one of the fields

At present I am putting the .keydown() on each input field although it works but this is making the script really long and i was wondering if there is a better way to handle it. This is what I am doing to individual fields to detect change

if ($("#some_field").length) {
    var timer = null;
    $('#some_field').keydown(function () {
        clearTimeout(timer);
        timer = setTimeout(update, 1000)
    });

    function update(){
        $.ajax({
            ...
            ...
            ...
    }
});
}
}

I will really appreciate any assistance here.


Create the function that you want to use for handling form submission. It gives you a chance to decide if you want to use ajax or default form submission:

function submitForm() {
   var form = $(this).closest('form')[0];
   form.submit();
   //or $.ajax( ... );
}

Then just use one selector for all input elements :input for example, or a common class and use the input event which will catch even when the user pastes text into one of the inputs:

$(':input').on('input', submitForm);

UPDATE

To listen to jQuery UI datepicker events too add change event as follows:

$(':input').on('input change', submitForm);

function submitForm() {
        var form = $(this).closest('form')[0];
        alert( 'About to submit form to ' + form.action );
       //form.submit();
       //or $.ajax( ... );
    }

    $(':input').on('input', submitForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="/form/update.php" method="post">
  Field 1: <input type="text" name="field1"/><br>
  Field 2: <input type="text" name="field2"/><br>
  Field 3: <input type="text" name="field3"/><br>
</form>

$('.class-of-your-inputs').change(function(){
   $("#you-form").ajaxSubmit({url: 'you_path.php', type: 'post'})
});
链接地址: http://www.djcxy.com/p/96932.html

上一篇: 如何在jQuery上处理多个事件

下一篇: 提交表单而不触及更新或提交按钮