views:

112

answers:

2

I'm using this code to display several forms on my page based on the link chosen by the user:

<ul class="nav">
   <li><a href="#" onclick="$('#more_info').toggle(); return false;">
      More Information</a>
   </li>
   <li><a href="#" onclick="$('#road_test').toggle(); return false;">
      Book a Road Test</a>
   </li>
   <li><a href="#" onclick="$('#quote').toggle(); return false;">
      Request a Quote</a>
   </li>
   <li><a href="#" onclick="$('#offer').toggle(); return false;">
      Make an Offer</a>
   </li>
   <li><a href="#" onclick="$('#contact').toggle(); return false;">
      General Contact</a>
   </li>
</ul>

The code works fine, the only issue I'm having with it is that if I select one form then select another one, the previously chosen form remains ie. if I select "More Information" then "Make an Offer", I'll get both forms instead of having just "Make an Offer". How do I fix this?

+2  A: 

You could store the form that is showing currently

var curForm;
function showForm(formId){
    if (curForm != null) curForm.hide();
    curForm = $(formId);
    curForm.show();
}

Then in your html

<ul class="nav">
   <li><a href="#" onclick="showForm('#more_info'); return false;">
      More Information</a>
   </li>
   <li><a href="#" onclick="showForm('#road_test'); return false;">
      Book a Road Test</a>
   </li>
   <li><a href="#" onclick="showForm('#quote');return false;">
      Request a Quote</a>
   </li>
   <li><a href="#" onclick="showForm('#offer'); return false;">
      Make an Offer</a>
   </li>
   <li><a href="#" onclick="showForm('#contact'); return false;">
      General Contact</a>
   </li>
</ul>
Zoidberg
Might want to get rid of the .toggle()s in the HTML.
moonshadow
Why use `toggle` when you know you want to `hide` the previous one and `show` the new one?
T.J. Crowder
Sorry, I don't normally use jquery, so I am not familiar with everything it offers.
Zoidberg
+1 = for the idea, but you don't need the `.toggle()` in the `onclick`
CAbbott
+1  A: 

This looks like a plug-in that jQuery offers http://docs.jquery.com/UI/Accordion If you want to pursue jQuery, this would be a good thing to use or at least look at it's source code.

Paul