Search code examples
jqueryformssubmitpreventdefaultconfirmation

Prevent submission of form until specified button clicked (thickbox dialog)


I would like to make a modal confirmation window using jQuery & thickbox on every form with 'confirm' class.

Here's the HTML markup:

<!-- The form below -->
<form id="myform" class="confirm" name="actionform" action="target.php">
<table>
  <tr>
    <td><input type="text" value="" placeholder="id" name="id" id="id"/></td>
    <td><input type="text" value="" placeholder="title" name="title" id="title"/></td>
    <td><input type="submit" value="Form elküldése"/></td>
  </tr>
</table>
</form>

<!-- The modal box and it's content below, called with tb_show() function -->
<div id="myModalConfirm" style="display:none">
    <div>
        <p>Are you sure?</p>
        <button id="yes">Yes, I'm sure</button><button id="cancel">No, cancel it</button>
    </div>
</div>

So the problem:

The modal dialog show up and works fine and the cancel button works but clicking on button#yes won't submit the form and I think it's because of the preventDefault() function.

Here's the jQuery (I'm working from jquery.1.8.3 lib, so please care about the compatibility )

$(document).ready(function(){
    $('form.confirm').submit(function(e){
        var form = $(this);
        e.preventDefault();
        tb_show("Megerősítés","#TB_inline?height=100&amp;width=200&amp;inlineId=myModalConfirm&amp;modal=true",null);
        $('button#yes').click(function(){
            $(form).submit;


            });
        $('button#cancel').click(function(){
            tb_remove();
            return false;
            });
    })

});

======| The solution |============================================================== It's for me but checkout the other goods below in comments :)

$('form.confirm').submit(function(e, submit){
        if (!submit) e.preventDefault();
        tb_show("Megerősítés","#TB_inline?height=100&amp;width=200&amp;inlineId=myModalConfirm&amp;modal=true",null);
    })

    $('#yes').click(function(){
        $('form.confirm').trigger('submit', [true]);
    });


    $('#cancel').click(function(){
        tb_remove();
    });

Solution

  • submit is a method not a property, you are missing (). You can use trigger method:

    $(document).ready(function(){
        $('form.confirm').submit(function(e, submit){
            if (!submit) e.preventDefault();
            tb_show("Megerősítés","#TB_inline?height=100&amp;width=200&amp;inlineId=myModalConfirm&amp;modal=true",null);
        })
    
        $('#yes').click(function(){
            $('form.confirm').trigger('submit', [true]);
        });
    
    
        $('#cancel').click(function(){
            b_remove();
        });
    });