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!

Nir
  • 3,963
  • 8
  • 37
  • 51

2 Answers2

3

Either

onchange="return foo();"

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

Or use the following jQuery

  $(function () {   //equivallent to: $(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
  • 13,192
  • 6
  • 42
  • 73
-1

Try setting the onchange value to:

onchange="return foo();"

that should do the trick normally.

Sam
  • 1,514
  • 2
  • 14
  • 22