views:

35

answers:

2

I have a select field that shows different elements of my form based on the selected value, I have three "classes" that each show the required portions of the filed. I currently have the selects bound to a .click() and it works fine except that if I want to load the page with the value preselected, it won't show the required parts of the form because the select field hasn't actually been clicked.

I've looked around and I don't see an event that would allow me to show information based on the selected value, but I'm not an expert so maybe I'm just misunderstanding some of the functions.

Here's the relevant portion of my HTML:

 <select name="class">
    <option value="vehicle" selected="selected">vehicle</option>
    <option value="part">Part</option>
    <option value="project">Project</option>
    <option value="vehicle">Vehicle</option>
 </select><br />
<etc...>

And my current jQuery switcher:

   $("select option[value='project']").click(function() {
      $('div.part-show').show().hide();
      $('div.both-show').hide().show();
      $('div.vehicle-show').hide().show();
   });

Thanks so much!

+1  A: 

You should use the change() event for the select tag.

$("select").change(function() {
  if ($("select").val() == "project") {
    $('div.part-show').show().hide();
    $('div.both-show').hide().show();
    $('div.vehicle-show').hide().show();
  }
});
Vasileios Lourdas
+1  A: 

I had a similar problem and what I did to get it to work is I fired off a click event (or a select event in my case) on the object I wanted preselected.

So...within your jQuery code do the following after you have setup your change function:

$('select option:first').click();

That should fire off your event and hide/show everything immediately.

Another option that works well is to start off with certain HTML shown and hidden based on what the default selected value is (just code it into the HTML). This works if you are going to have a static default selected value (AKA, it is not dynamic based on other user input).

JasCav