1

I am using a jquery ui dialog as a prompt. The "prompt" has to buttons, "Ok" and "Cancel". The problem here is, it extracts the input fields value in the dialog when .dialog("close") is triggered and my only validation is that the length of the input field has to be more than 0 chars. This means that even when you type something and press cancel the text from the prompt will be submittet. My thought was to find out what button was pressed... Anyone know a solution to this?

My current event code:

$("#addBusinessarea").click(function(){
    createPrompt("Add new business area", "Business area name:");
    $( "#prompt" ).bind( "dialogclose", function(event, ui) {
        if($("#promptValue").val().length > 0){
            // Add business area 
        }
    });
});
Thor A. Pedersen
  • 1,122
  • 4
  • 18
  • 32
  • 1
    It would be much better to simply bind your event handler to the form's submit event. – Niko Sep 06 '11 at 12:09

2 Answers2

1

Old question, but this question came up for me, and I found the right answer, with help from jQuery UI Dialog buttons

event.target is your button.

$( "#prompt" ).bind( "dialogclose", function(event, ui) {
    if ($(event.target).text() != "Cancel") {
        if($("#promptValue").val().length > 0){
            // Add business area 
        }
    }
});
Community
  • 1
  • 1
Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
  • The worst thing is, its an old question I accidently forgot about. I don't work at the place where the problem came up, so i am not sure what the problem was exactly.. but your solutions seems to focus on what text is in the button.. what if the system was language sensitive, then the button, in some cases, would not have "Cancel" as the text. But thanks for noticing the question :-) – Thor A. Pedersen Aug 11 '13 at 12:52
  • @ThorA.Pedersen My major point was that you use `$(event.target)` to get the button that was pressed, and `$(event.target).text()` to get the text of that button. From there, you can check however/whatever you want. That's what I was hoping to see based on the question title. :-) – Scott Mermelstein Aug 11 '13 at 15:02
1

To properly solve change the way you've defined buttons for jQuery UI dialog. It can look like this (notice that you can have different click handlers for different buttons):

$("#modal").dialog({
        buttons: {
            Yes: {
                text: 'Yeeees!',
                click: function() {
                    alert('I clicked yes!');
                }
            },
            No: {
                text: 'Hell no!',
                click: function() {
                    alert('I clicked no!');
                }
            }
        }
    })
WTK
  • 16,583
  • 6
  • 35
  • 45