Question

I am trying to save a user's input once they have clicked on another control on the page. I had a look at the focusout event but it fires every time user enters value or selects another control. here is how i used it:

        $('#txt_ComplainingAbout').focusout(function (e) {
             $.ajax({
                    type: "POST",
                    url: "Form.aspx/Save",
                    data: "{'id': '" + this.value + "','value': '" + this.value + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",

                    success: function (msg) {
                        if (msg.d == 'success') {

                        }
                    }

                });
            e.preventDefault();
        });

Is there any other way to call the above ajax call per control?

Was it helpful?

Solution

Would the blur event not give you the behavior you want?

Also, have you looked at a delegated event? With a delegated approach you use a single event handler to deal with events raised by multiple elements. So if you had a table with 10,000 cells, and you wanted to perform some action on click, instead of attaching an event handler to every one - which would be costly for performance - we attach one event handler to the table which is delegated to handle all events.

So following this paradigm, you could always have a single event handler for a form which handles every input in that form.

$("form").on("blur", ":input", function(e) {
    // this refers to whichever form element triggered the event
    var $this;

    $.ajax({
        type: "POST",
        url: "Form.aspx/Save",
        data: "{'id': '" + $this.attr("id") + "','value': '" + $this.val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (msg) {
            if (msg.d == 'success') {

            }
        }

    });

    e.preventDefault();

});

OTHER TIPS

Try something like below.

 $('#txt_ComplainingAbout').unbind('focusout').bind('focusout', function (e) {

    //your code
    return false; //to prevent the browser actually following the links!

});

EXPLANATION

focusout(function() {} method is a shortcut for .bind('focusout', handler).

For more information check .focusout()

By using above way (unbind/bind) you can sort it out issues like when click button once it fires 2 times or the issue your having kind of.

I hope this will help to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top