views:

35

answers:

2

I want to show a confirmation dialog when a specific value is selected in an asp:DropDownList. If the confirmation dialog returns false (cancel) then I want to prevent the AutoPostBack.

<asp:DropDownList id="theDropDownID" onchange="foo()"></asp:DropDownList>

However, it ignores the returned value from foo() and actually does the postback.
The generated code of the onchange event is:

foo(); setTimeout("__doPostBack('theDropDownID','')", 0);

so basically controlling the setTimeout that the .net adds, will do the job.

Any idea how?
Thanks!

+1  A: 

Either

onchange="return foo();"

function foo() {
    //do whatever
    return false;
}

Or use the following jQuery

  $(document).ready(function() {
        $('#theDropDownID').removeAttr('onchange');  
        $('#theDropDownID').change(function(e) {  
            e.preventDefault();  
            if (confirm("do postback?")) {
             setTimeout('__doPostBack(\'theDropDownID\',\'\')', 0);
            }
        });
   });

I prefer the second approach because it is unobtrusive javascript: all of the behaviour is together and there is no inline javascript at all.

Daniel Dyson
thanks man, your jQuery helped!
Nir
A: 

Try setting the onchange value to:

onchange="return foo();"

that should do the trick normally.

Sam