views:

1328

answers:

1

I have a form with some select elements that have onChange events attached to them. I would like the event to fire even when someone clicks the form reset button.

My question is: does resetting a form fire a select elements onChange event?

Here is a simple example in jQuery

<script type="text/javascript">
    $('.myselect').change(function() {
        // do something on change
    });
</script>

<form action="/" method="post">
    <select class="myselect" name="select1">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <select class="myselect" name="select2">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <!-- When this is clicked I would like it fire the change event -->
    <input type="reset" value="Reset" /> 
    <input type="submit" value="Save" />
</form>

Thanks!

A: 

There is an onReset tag for forms, so you could do something like:

<script type="text/javascript">
    var changeFunc = function() {
        // do something on change.
    };
    $('.myselect').change(changeFunc);
</script>

<form onReset="changeFunc()" action="/" method="post">
    <select class="myselect" name="select1">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <select class="myselect" name="select2">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <!-- When this is clicked I would like it fire the change event -->
    <input type="reset" value="Reset" /> 
    <input type="submit" value="Save" />
</form>

This method is called before the reset happens, though so it can be tricky. I guess so you can do an "Are you sure?" box. Tossing a setTimeout in the reset function seems to do the trick.

Jack M.

related questions