Question

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

Was it helpful?

Solution

$('#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.

OTHER TIPS

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>

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;
}

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.

Better version:

$('#select').change(function() {
   $('div').not('#form' + $(this).find('option:selected').attr('id')).hide();
   $('#form' + $(this).find('option:selected').attr('id')).show();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top