如何在focusout()上提交Ajax表单

时间:2013-11-25 17:22:17

标签: javascript jquery ajax

我有以下表格,由AJAX提交:

HTML

<form class="form-horizontal" id="formEditUsername" action="<?php echo URL; ?>account/editusername_action" method="post">
  <input type="text" class="form-control" name="user_name" id="user_name" placeholder="Add username" value="User ">
  <button type="submit" class="btn btn-default">Save</button>
</form>

AJAX

$("#formEditUsername").submit(function(event){
        //disable default click operation
        event.preventDefault();

        var action_url = $(this).attr("action");
       $(".help-block.username").hide().html("<i class='fa fa-refresh fa-spin'></i> &nbsp;&nbsp;Processing...").fadeIn('slow');
       console.log(action_url);
       var postData = $(this).serializeArray();
        //console.log(postData);

        $.post(action_url,postData,function(data){

            console.log(data);
            var obj = $.parseJSON(data);
            $(".help-block.username").html("Saving...");

            if(obj.status == "error")
            {
            $(".help-block.username").css({color: '#990033'});
            $(".help-block.username").html(obj.message).fadeIn('slow');

            };

            if(obj.status == "success")
            {
                $(".help-block.username").css({color: '#00b25a'});
                $(".help-block.username").html(obj.message).fadeIn('slow');
                $(".namebox").html(obj.username);
            }
        });

    });  

我想添加一个功能,以便在输入(#user_name)失去焦点后,表单以focusout()提交。有什么想法吗?

3 个答案:

答案 0 :(得分:4)

$('#user_name').on('focusout', function() {
    $("#formEditUsername").trigger('submit');
});

阅读本文:http://api.jquery.com/focusout/

答案 1 :(得分:3)

$('#user_name').on('blur', function() {
    $("#formEditUsername").trigger('submit');
});

答案 2 :(得分:2)

要提交表单,请使用:

$('#user_name').on('focusout', function() {
    $("#formEditUsername").get(0).submit(); // this fires JS native event, not jquery handler
});