views:

38

answers:

4

Hi, this problem is part of a bigger page but I've simplified the code to provide an easy example of what I'm talking about. Basically I have an ASP dropdownlist with AutoPostBack="true" and I want to do some javascript client side which can stop the postback if necessary. However, I can't get it to stop the postback.

<script type="text/javascript">
$(document).ready(function()
{
    $("#ddl").bind('change', function() {
        return false;
    });
});
</script>

<select id="ddl" onchange="form.submit()">
    <option value="">Item 1</option>
    <option value="">Item 2</option>
    <option value="">Item 3</option>
    <option value="">Item 4</option>
    <option value="">Item 5</option>
</select>
A: 

Try this:

$(document).ready(function() {
  $('#ddl').attr('onchange', '').change(function() {
    if (0 !== +$(this).attr('selectedIndex')) {
      this.form.submit();
    }
    return false;
  });
});
jmar777
Yes this will overwrite the form.submit embedded in the tag but I need to catch the onChange event and then if certain criteria aren't met, not let the page proceed with a PostBack.
rpf3
@rpf3: Ahh, sorry I missed that. Does the updated snippet closer to what you're looking for?
jmar777
That is, thanks, but I posted a more detailed explanation of the problem on patrick dw's answer
rpf3
Heh... new attempt. It will block a submit() if the select has an empty value, otherwise it goes through. Edit: updated again to explicitly check the selectedIndex, rather than the value.
jmar777
A: 
$("#ddl").change(function() {
    // Do some javascript
    return false;
});

Also, it might help if you take the onChange attribute off the select element

Zane Edward Dockery
This is exactly equivalent what the OP already has.
Nick Craver
Your code example is effectively the same as the code in the question.
patrick dw
A: 
$("#ddl").change(function(e) {
    e.preventDefault();
});
Marko
Doing `e.preventDefault()` wouldn't actually do anything more to prevent the form from submitting than the `return false;`.
patrick dw
A: 

This is my workaround (Firefox works, IE 7/8 works):

$(function() {
    var $select = $('#ddl'), tmp = $select.attr('onchange');

    $select.attr('onchange', '');

    $select.change(function() {
        // If you want to postback:
        tmp();
    });
});

Simple removes the HTML handler and puts it into a variable. Then you can register your change function and if you want to call the auto postback function you can.

Bob Fincheimer
Other people have submitted something similar but I went with this. Thanks!
rpf3