Jquery events on input fields

advertisements

I have a problem with jquery submit button onclick and default event. What I want to do is replace an click event on submit button if it has one, and get an dialog box to show up, on clicking yes the dialog should start that default onclick event if submit button has one defined, if it hasn't than the default event should happen (button submits form), .submit() function does not work for me in any case cause I need to send this button also through a form and if button wasn't clicked .submit() sends form data without submit data.

Bellow code has a problem, alert('xxx') is always called and it shouldn't, and on clicking yes button alert and dialog creation is called again, also if I remove alert button, I cannot call default submit button event (form submitting with a button).

$('input.confirm').each(function(){
    var input = this;
    var dialog = document.createElement("div");
    $(dialog).html('<p>AREYOUSHURE</p>');
    $(input).click(function(event)
    {
        event.preventDefault();
        var buttons = {};
        buttons['NO'] = function() { $(this).dialog("close"); };
        buttons['YES'] = function() { $(input).trigger('click'); $(this).dialog("close"); };

        $(dialog).dialog(
        {
            autoOpen: false,
            width: 200,
            modal: true,
            resizable: false,
            buttons: buttons
        });
        $(dialog).dialog('open');
        return false;
    });
});

<form method="post" action="">
    <input type="hidden" value="1" name="eventId" />
    <input type="submit" value="Check" name="checkEvent" class="confirm" onclick="alert('xxx');" />
</form>


When you add an onclick event it will run indepent of any jquery. It's considered good practice not to use onclick if you are mixing with jquery.

A better solution:

var buttons = {};
var dialog = document.createElement("div");
$(dialog).html('<p>AREYOUSHURE</p>');
$('.confirm').click(function(event){
    event.preventDefault();
    var input = $(this);
    buttons['NO'] = function() { $(this).dialog("close"); };
    buttons['YES'] = function() { $(input).trigger('click'); $(input).closest('form').submit(); $(this).dialog("close"); };

    $(dialog).dialog(
    {
        autoOpen: false,
        width: 200,
        modal: true,
        resizable: false,
        buttons: buttons
    });
    $(dialog).dialog('open');
    return false;
});

Make buttons of global scope. Then when you click yes simply submit the form