Why can't I trigger a submit button from within jQuery UI Dialog?
Asked Answered
O

13

16

EDIT:

Some people have suggested calling submit directly on the form. This is not what I am trying to achieve. I want, specifically, to be able to call the click() event on an input type='submit' and have it submit the form like it normally would. jQuery UI Dialog appears to be interfering with this normal behavior. Please check out the jsFiddle link I have created, as the problem is re-creatable on there.


( First off I have already seen this question on StackOverflow, but the answer does not work in my situation: jQuery UI Dialog with ASP.NET button postback )

Desired Behavior:

On my page I have both a hidden field and a submit button (which is hidden via CSS).

What I want to do is use JavaScript to programmatically click this button, thereby causing the form to be submitted. Most importantly.... I want to trigger all of this from inside of a jQuery UI Dialog. Basically, the user will be making a selection inside the jQuery UI dialog that will cause the whole page to be submitted and reload.

Problem Statement

Triggering a button click like this normally works fine to submit the form. However, it fails when the action is triggered from within a jQuery UI Dialog.

As you can see in my jsFiddle code, I call jQuery's click() function on the submit button.... but the form does not actually submit! The button is indeed getting clicked by the JavaScript, but the "form submit behavior" does not occur itself. The page is not posted.

I believe the jQuery UI Dialog is somehow interfering with the form submit behavior of the button I am trying to programmatically click.

The reason I want to programmatically trigger the button click:

I cannot have the buttons located inside the dialog be submit buttons themselves. In my case, I have created a reusable JavaScript control that wraps a jQuery UI Dialog. This JS control allows the users to pick an employee. However, when an employee is picked, the desired behavior is not always going to be: form submit. (Sometimes I might want to display the picked employee on the page and not perform a submit yet.)

Additional details:

This problem is not specific to ASP.NET, but here are some additional details to help explain why I am attempting all this. I am writing an ASP.NET Web Forms app using .NET 4.5. I have begun to use JavaScript more and more for my pages, but on this particular page I want to trigger an actual postback to the server so I can handle a button click event from the ASP.NET page life cycle and populate a GridView. That is why I want to be able to use JavaScript to click an asp:button that, in turn, causes a form submit.

And most importantly... Try it Yourself ---> See jsFiddle link below.....

Again, this issue it not specific to ASP.NET. I have been able to recreate the same issue here on JsFiddle using regular HTML and jQuery UI. Here is the JsFiddle link:

http://jsfiddle.net/fENyZ/18/

As you can see in the code, I already attempted to use the "fix" of moving the jQuery UI Dialog inside the form via jQuery DOM manipulation. This does not appear to fix the issue.

Thanks! I appreciate any help!

HTML

<html>
<head></head>
<body>

    <form action="http://www.google.com/index.html" method="post">

        <input type="button" value="Open jQuery dialog" id="btnOpenDialog" />
        <br /><br /><br />

        The button below submits the form correctly if you click it.<br />
        However, when I try to trigger click() event on this button <u>from within the jQuery UI Dialog above</u> then the form <b>fails to be submitted.
        </b><br />

        <input type="submit" value="Submit Form" id="btnSubmitForm" />  
        <input type="hidden" id="hdnEmployeeChosen" value="" />            
    </form>    


    <div id="divPopup" class="dialogClass" style="display: none;">
        Picking an employee below <b>ought to</b> cause the form to submit, but sadly it does not...
        <br /><br />

        <div class="divOptions">
            <input type="button" value="Pick" class="pickButton" employeeName="Weird Al" />
            Weird Al Yankovic
        </div>
        <div class="divOptions">            
            <input type="button" value="Pick" class="pickButton" employeeName="Dracula" />
            Count Dracula
        </div>
        <div class="divOptions">          
            <input type="button" value="Pick" class="pickButton" employeeName="David" />
            David Copperfield
        </div>        
    </div>

</body>

JavaScript

$(document).ready(function ()
{
    var jqueryDialog = $('#divPopup')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    title: 'My Dialog',
                    width: 300,
                    height: 300,
                    draggable: false,
                    resizable: false
                });

    // This "fix" does not appear to help matters..........
    jqueryDialog.parent().appendTo($("form:first"));

    $('#btnOpenDialog').click(function () {
        jqueryDialog.dialog('open');    
    });    

    $('.pickButton').click(function () {

        // Put picked value into hidden field
        var pickedEmployee = $(this).attr('employeeName');
        $('#hdnEmployeeChosen').val(pickedEmployee);

        // Try to cause a submit (ASP.NET postback in my case)        
        // THIS PART DOES NOT WORK.................
        $('#btnSubmitForm').click();

        //alert($('#hdnEmployeeChosen').val());
    });    

});

CSS

form {
margin: 5px;
    border: 1px solid black;
    background-color: #EEE;
    padding: 15px 5px;
}

.dialogClass {
 border: 1px solid black;
padding: 5px;
margin: 5px;
    background-color: LightBlue;
    font-size: 14px;
}

.pickButton {
  margin-right: 5px;   
}

.divOptions {
   margin-bottom: 3px;   
}
Obstetrician answered 18/10, 2012 at 23:3 Comment(0)
O
6

Just had a similar issue where I could step through the right submit button executing, but the form was just not submitting. After stepping through the jquery dialog code and not finding how it could keep the event from propagating, I just decided to do the obvious and hide the dialog right before submission. Works on your fiddle too: http://jsfiddle.net/Q4GgZ/1/

jqueryDialog.dialog('close'); // <- THIS WORKS
$('#btnSubmitForm').click();
Ofris answered 14/1, 2014 at 20:40 Comment(2)
Per the jquery-ui docs for modal dialogs: "If set to true, the dialog will have modal behavior; other items on the page will be disabled, i.e., cannot be interacted with. Modal dialogs create an overlay below the dialog but above other page elements." -- What the docs don't say is what "disabled" actually means. It means that anything below the overlay will have the events disabled while the dialog is open. The reason setTimeout is another fix for this problem is because the dialog is closed by the time it executes and the events are no longer disabled at that point.Joinery
Not sure what they mean by that either. Pre-jQuery, I implemented my own modals by having an overlay intercept all of the click events and literally applying the "disabled" attributes to inputs/selects/buttons/etc to prevent tabbing. The form element itself doesn't support the disabled attribute, so I'm still curious what mechanism they are using. Still haven't had a chance to do more research.Ofris
P
5

I had the same problem and the following set of suggestions worked for me.

  1. Append the dialog to the form $(this).parent().appendTo("form:first");
  2. Append the dialog to the form within the dialog's open option

Credit goes to Homam and his comment on another question.

See below JavaScript

    var jqueryDialog = $('#divPopup')
        .dialog({
            autoOpen: false,
            modal: true,
            title: 'My Dialog',
            width: 300,
            height: 300,
            draggable: false,
            resizable: false,
            open: function() {
                $(this).parent().appendTo('form:first');
            }
        });
Plug answered 10/2, 2015 at 17:18 Comment(1)
I found it was better to call $('#divPopup').parent().appendTo('form:first'); immediately after creating the dialog, and not waiting until it was open, via the open method, else ASP.NET webforms can't see the controls to set their values.Randallrandan
L
2

If someone is still looking for an answer, here is something that worked for me.

setTimeout("$('#" + id + "').click();", 0);

id is e.currentTarget.id where event is click of submit button. Pass that id to the method that has to trigger the click event.

.trigger("click") doesnt trigger postback, but the above code does.

Lupine answered 29/3, 2013 at 2:17 Comment(0)
P
2

As LouD mentioned, the fix is to close the dialog before "clicking" your button. As for why this fixes anything, you need to dig into the JQuery UI source. In version 1.8.9 there is this code for the modal overlay:

events: c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","), function (a) {
    return a + ".dialog-overlay"
}).join(" "),

...

c(document).bind(c.ui.dialog.overlay.events, function (d) {
    if (c(d.target).zIndex() < c.ui.dialog.overlay.maxZ) return false
})

It's returning false (basically preventDefault()) for all input events on elements "under" it. It's not just a giant div that prevents the user from clicking things by being "over" them. It's also manually blocking all input events, whether the user or your JS generated them.

Closing your modal dialog destroys the overlay, which allows your JS click events to fully propagate, submitting the form.

Pisa answered 14/7, 2014 at 20:0 Comment(0)
L
1

Assign an id attribute to your form:

<form id="myForm" action="http://www.google.com/index.html" method="post">

then submit the form:

$('.pickButton').click(function (e) {
  e.preventDefault();
  $('#myForm').submit();
  // more code
}
Letreece answered 18/10, 2012 at 23:23 Comment(1)
Under the Additional details section I mentioned I am attempting to handle the submit action using ASP.NET's page life cycle and button click event on the back end. The fact I am using ASP.NET is not important in recreating this issue. However, it does explain why I want to actually use the submit button to cause the postback. Performing a submit on the form element itself is not sufficient to trigger the button click event on code-behind. This is the reason I am trying to focus my question on: how can I make this all happen using the submit button itself.Obstetrician
H
0

I'dont see the code for the Click event of the submit Button..

Instead of

$('#btnSubmitForm').click();

Try

$('form').submit();

Or submit the form in the click event handler of your submit button.

Hexameter answered 18/10, 2012 at 23:8 Comment(1)
Thanks for the reply. If you could please see my comment to user1757786's answer. I need to have the button itself trigger the form submit. I am aware I can get a handle on the form and submit it manually, however it is not ideal. The point of my question is to find out how to make the submit button itself work like it should. Also, there isn't any code needed for the submit button... its type='submit', so it will cause a form submit. Try manually clicking on it inside jsFiddle and see it submits.Obstetrician
Q
0

The submit button is being clicked. I added the following code to your script...

$("#btnSubmitForm").on("click", function() {
    console.log("submit!");
});

and that shows that the button is clicked.

As Sushanth said, use the submit() method of the form, or if you want to trigger postback for asp.net then look into __doPostBack()

How to use __doPostBack()

Quan answered 18/10, 2012 at 23:10 Comment(2)
Thanks for the reply. As I mentioned, I am aware the button is indeed "being clicked".... but the issue is that the button is not performing the form submit action it normally would. It is very strange, because only half of the expected behavior is occurring. In your example above, the console.log occurs when clicking the button.... yet.... the form submit does not occur. If you go into the jsFiddle and just manually click the submit button I put there, you will see it does submit normally. (Sushanth's solution doesn't solve the question I am posing... you can see my comment up there.)Obstetrician
Yesterday, I tried using __doPostBack() to trigger the form submit as well... but that didn't seem to work either. That is why I recreated the issue using only HTML and jQuery UI through jsFiddle. This way people could see it wasn't related specifically to ASP.NET. It is a problem in general. I think that if a solution could be found to this generic problem, then I would be able to apply that problem to my specific situation (in this case, ASP.NET).Obstetrician
M
0

This could be a bug, depend on your version of jQuery

look at this article about the same problem

In all case, as you want to submit your form, the shortest way is to use the .submit() method.

Murrelet answered 18/10, 2012 at 23:16 Comment(1)
Thanks for the reply. It is quite possible in my mind this is a jQuery bug. I checked the link you posted and he was using jQuery 1.4 which had the bug. I am using jQuery 1.8 (you can check this on my jsFiddle example link), which the guy claims has the bug already fixed.Obstetrician
H
0

because it copy Multiple oject. so you can use : $('[id="btnCreate"]').last().trigger('submit');

last method get last element .

you update $('#btnSubmitForm').click();

try to this : $('[id="btnSubmitForm"]').last().trigger('click');

$('[id="btnSubmitForm"]') get all the same id for btnSubmitForm.

for example:

$("#dialog").dialog({
            autoOpen: false,
            //maxWidth: 600,
            //maxHeight: 500,
            minWidth: 580,
            width: 580,
            height: 500,
            title: "titleDemo",
            show: {
                effect: "blind",
                duration: 1000
            },
            hide: {
                effect: "explode",
                duration: 1000
            },
            modal: true,
            buttons: {
                "Create": {
                    text: "OK",
                    id: "btnCreates",
                    click: function (event) {
                        $('[id="btnCreate"]').last().trigger('submit');
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
Heron answered 5/12, 2013 at 8:42 Comment(2)
I tried your idea about using last(), but it hasn't improved the situation. See my updated jsFiddle... jsfiddle.net/fENyZ/28Obstetrician
Ok I tried the jsFiddle... and I see the alerts going off.... but on the last alert that says "submit".... it does not actually submit the form. This is the root of the problem.Obstetrician
O
0

The problem is caused by using a id element as a selector... When the jquery ui dialog is called, it copies in the desired block into a generated container, this means that specific identifiers like #form_name now will have duplicates confusing the jquery selector...

my solution would be to switch to a class identifier, then use a more specific path to select the button ex: $(jQuery_dialog_box. class name).submit() (or click() )

Oligocene answered 9/12, 2013 at 23:46 Comment(1)
I don't think the problem is with the selector. I am correctly selecting the submit button and correctly causing the click event to fire on it. You can see this by putting a console.log on the click event for the button, as mentioned by others. The problem is that when the button is programatically clicked..... (which it is).... it fails to submit the entire form like it would if you manually clicked on it with your mouse.Obstetrician
O
0

The Jquery UI dialog by default prevents any buttons from submitting (at least base on my experience so far). With that said, I figured out that if you change the "submit behavior" on any button to "False" through Visual Studio it then works. I know this is totally opposite of what it should be but if you do this then buttons inside the JQuery UI Dialog will post back and work.

I also found after a couple hours that any fields within a JQUI Dialog are not recognized in ASP.net on post back unless you call the destroy method on the Jquery UI dialog object.

I was really liking this control until I started getting into the gritty details of using it with a real application and other than basic pop ups I'm not sure this control is fully ready for prime time yet.

Outrush answered 11/12, 2013 at 0:25 Comment(0)
S
0

I arrived here with a very similar problem, but as i lost some hours with this problem i post it for future readers.

There are some problems with this code:

  1. If the dialog is modal, it seems that you can't trigger events for other elements outside the dialog. If you make the dialog with the option modal : false, the trigger will works ok. I want that the dialog was modal, so this solution is not an option.

  2. As the dialog is modal, you have to put the button inside the dialog. You can hide it and trigger through your classed buttons. I modify the javacript section and tried on fiddle and works for your case.

HTML

<form action="http://www.google.com/index.html" method="post">

    <input type="button" value="Open jQuery dialog" id="btnOpenDialog" />
    <br /><br /><br />

    The button below submits the form correctly if you click it.<br />
    However, when I try to trigger click() event on this button <u>from within the jQuery UI Dialog above</u> then the form <b>fails to be submitted.
    </b><br />


    <input type="hidden" id="hdnEmployeeChosen" value="" />            

    <div id="divPopup" class="dialogClass" style="display: none;">
    Picking an employee below <b>ought to</b> cause the form to submit, but sadly it does not...
    <br /><br />

    <div class="divOptions">
        <input type="button" value="Pick" class="pickButton" employeeName="Weird Al" />
        Weird Al Yankovic
    </div>
    <div class="divOptions">            
        <input type="button" value="Pick" class="pickButton" employeeName="Dracula" />
        Count Dracula
    </div>
    <div class="divOptions">          
        <input type="button" value="Pick" class="pickButton" employeeName="David" />
        David Copperfield
    </div>     

       <input type="submit" value="Submit Form" id="btnSubmitForm" style="display:none"/>  
</div>

</form>    




</body>

JAVASCRIPT

$(document).ready(function ()
{
var jqueryDialog = $('#divPopup')
            .dialog({
                autoOpen: false,
                modal: true,
                title: 'My Dialog',
                width: 300,
                height: 300,
                draggable: false,
                resizable: false
            });

// This "fix" does not appear to help matters..........
jqueryDialog.parent().appendTo($("form:first"));

$('#btnOpenDialog').click(function () {
    jqueryDialog.dialog('open');    
});    

$('.pickButton').click(function () {

    // Put picked value into hidden field
    var pickedEmployee = $(this).attr('employeeName');
    $('#hdnEmployeeChosen').val(pickedEmployee);

    console.log("click button dialog");
    // Try to cause a submit (ASP.NET postback in my case)        
    // THIS PART DOES NOT WORK.................
    $('#btnSubmitForm')[0].click();

    console.log("after click");        
    //alert($('#hdnEmployeeChosen').val());
});    

});

You can see in fiddle here

Slapup answered 5/2, 2015 at 17:11 Comment(0)
H
0

The simple solution to this problem is to set the submit event after the dialog is opened. It is not necessary to close the dialog before the submit event will fire.

When the dialog is overlaid during the .open() method all events are disabled. So setup the events you need after the dialog is opened.

$('#btnOpenDialog').click(function () {
        jqueryDialog.dialog('open');   
     // now setup events 
        $('#btnSubmitForm').on('click', function() {
            // process submit event 
        });
}); 
Hideandseek answered 26/8, 2016 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.