views:

3146

answers:

4

my code:

<select id="select">
<option id="1" value="thai language">option one</option>
<option id="2" value="eng language">option two</option>
<option id="3" value="other language">option three</option>
</select>

<div id="form1">content here</div>
<div id="form2">content here</div>
<div id="form3">content here</div>

what i want is to show div #form1 when select option 1 and hide form2+form3, or select option 2 show div#form2 and hide form1+form2

+2  A: 
$('#select').change(function() {
   $('#form1, #form2, #form3').hide();
   $('#form' + $(this).find('option:selected').attr('id')).show();
});

Do note that IDs should not start with numbers, but the above should do it.

Paolo Bergantino
Along the lines of what I was thinking. $(this).attr('id') won't refer to the id of the select itself? I was thinking I'd have to get the select index, grab that option, and then get the id.
Jonathan Sampson
Good catch, fixed.
Paolo Bergantino
Just to add to the comment above, add a class to the 'content here' divs of say 'contentBox' then $('.contentBox').hide(), saves listing all the seperate divs.
Nooshu
++ Paolo. Nooshu, true, but I don't think Paolo was interested in offering better markup, only the solution the asker requested with the given markup.
Jonathan Sampson
Actually, .contentBox would have to get *all* the elements in the document and see if they have the class, three ID lookups could actually be faster depending on the document. div.contentBox, however, would probably be best if the amount of forms grow, but for this situation I don't think it's necessarily bad to have it as it is, although I did think about suggesting a common class.
Paolo Bergantino
couldn't you have just used .val()?
j3frea
.val() would get "option one", etc. not the numeric 1, 2, 3.
Paolo Bergantino
it's not work. how you do that?
vee
ok .i forget to add $(document).ready(function(){ // Your code here });:-Pthank you very much.
vee
A: 

Something like this?

var optionValue = $("#select").val();

$('#form1, #form2, #form3').hide();

switch(optionValue)
{
case 1:
  $("#form1").show();
  break;
case 2:
  $("#form2").show();
  break;
case: 3:
  $("#form3").show();
  break;
}
Tom
A: 

Wouldn't it be better to only hide the previously shown div? So;

var selection = 0;
$('#select').change(function() {
  $('#form' + selection).hide();
  selection = $(this).val();
  $('#form' + selection).show();
});

Do note that IDs should not start with numbers, but the above should do it.

j3frea
A: 

If your forms are large, you can put them in separate files like this,

$(document).ready(function() {
     $('#select').change(function() {
         $("#myform").load(this.value);
     });
 });


<select id="select">
<option value="blank.htm">Select A Form</option>
<option value="test1.htm">option one</option>
<option value="test2.htm">option two</option>
<option value="test3.htm">option three</option>
</select>

<div id="myform" ></div>
Tony Borf