Search code examples
jqueryformssubmitconfirmfocusout

Jquery focus out event and then submits the form


I have a form textbox having focusout event on it. when the textbox loses focus, a confirm box pops, ask for "Ok" or "Cancel".

If user click Ok, form submits. How to do to accomplish this?

I tried this, but no luck:

//<![CDATA[ 
$(function(){
$('#item_new').focusout(function() {
confirm("add this item?");

        'Confirm submit': function() {
            currentForm.submit();
        },
        Cancel: function() {
            $(this).dialog('close');
        }

});
});
//]]> 

please advise.


Solution

  • When you decompose your code, you'll see that the confirm and rest are not linked at all.

    Here is some code that can help:

    $('#item_new').focusout(function(e){
    
        // ask the user and keep his/her choice
        var ok = window.confirm('add this item?');
    
        // here, the 'ok' variable will be 'true' if OK was clicked,
        // false otherwise
        if( ok ) {
           // do the submit action.
           // replace '<id_of_the_form_to_submit>' with the id of the form
           $('#<id_of_the_form_to_submit>').submit();
        }
    });
    

    See this jsfiddle: http://jsfiddle.net/arnaudj/c6z44mr9/

    Edit: note that the window.confirm call will make a basic browser-specific confirmation popup pop and that you cannot "decorate" as you want with style.