Today I ran into a problem when working on a site for a client. We have a form with two select’s. The left one is “available persons” to choose from and the right one is the persons that the user has chosen. To choose a person and “move” it to the right select the user clicks on the person and then on a link that moves the option to the right select. So far so good, but when I pressed Submit I was (stupidly) surprised that I didn’t get the results I was expecting in the POST variable. The “available persons”-POST-variable was completely empty, but if I tried to move all persons to the right select and back again it worked.

After talking about it with a coworker it was perfectly logical, because the options was not selected when the form was submitted. Realizing that if I didn’t get the problem directly our client’s users will neither, so we had to come up with a solution. The solution is pretty easy actually, because I love easy solutions this was perfect.

What we do is that we hook on the the submit click event and select all options if they are not already selected. So now users don’t need to worry about selecting all options. From the user’s point of view the just need to get the person in the correct option box.

The jquery code is pretty simple and self explaining, but very quickly we will put an click event on the submit button. When the button is clicked we go through our two selects and use each to go through the options and set “selected = selected” which means that they are selected. Last but not least we submit the form. Simple, but it can take some time to figure it out so we post the solution here for others.

$(document).ready(function() {
  $("#submitId").click(function() {
    $("#optionsId1").each(function(){ $("#optionsId1 option").attr("selected","selected"); });
    $("#optionsId2").each(function(){ $("#optionsId2 option").attr("selected","selected"); });
    $("#submitId").submit;
  }) ;
});

Similar Posts:

  • Share/Bookmark