jQuery function resetting other form field

jQuery function resetting other form field

I have a web ui that allows someone to add/remove users to/from roles.

The page has a select box with the available roles, with a submit button next to it to allow the user to change which role is being assigned/revoked.

I then have two multiselect fields one listing people unassigned to the role, the other listing people currently assigned to the role.

I have two non-submit buttons that my jQuery script intercepts and moves entries between the two multiselect boxes so users can be assigned or revoked from the currently selected role.

The jQuery script looks like this:

  1. <script type="text/javascript">
  2. $().ready(function () {
  3. $('#add').click(function () {
  4. !$('#unassigned option:selected').remove().appendTo('#assigned');
  5. return $("option:selected").removeAttr("selected");
  6. });
  7. $('#remove').click(function () {
  8. !$('#assigned option:selected').remove().appendTo('#unassigned');
  9. return $("option:selected").removeAttr("selected");
  10. });
  11. $('form').submit(function () {
  12. $('#unassigned option').each(function (i) {
  13. $(this).attr("selected", "selected");
  14. });
  15. $('#assigned option').each(function (i) {
  16. $(this).attr("selected", "selected");
  17. });
  18. });
  19. });
  20. </script>

The script works, however it is having an undesired effect:

After the jQuery script correctly moves the selected users between the two multiselect fields, the select field controlling which role is being assigned/revoked gets reset to the default (first) role.  How can I prevent this from happening?