Ken Hollis
Ken Hollis

Reputation: 71

Show each form and hide other form after selecting an option

I want to make a dropdown list using <select</select> named Classification and it has 2 form, Resident and Business. If the user choose Resident option a form will show up after clicking the 1st option and if the user choose Business form a different form will show up.

I found this code from the internet:

<select>
    <option value="" selected="selected"></option>
    <option value="form_1">Form 1</option>
    <option value="form_2">Form 2</option>
</select>

<form name="form_1" id="form_1" style="display:none">
    <input type="text" value="1">
</form>

<form name="form_2" id="form_2" style="display:none">
    <input type="text" value="2">
</form>

JS:

$("select").on("change", function() {    
    $("#" + $(this).val()).show().siblings();
});

My problem is I want to show the form each. For example user choose Resident only Resident form will show up and the other form will be hidden.

Hope you can help me in my problem Thanks in Advance (sorry for bad english)

Upvotes: 0

Views: 188

Answers (3)

Shyam
Shyam

Reputation: 792

$("select").on("change", function() {    
  $(this).siblings('form:visible').hide(); // if blank option selected, all form will should be hide
  $("#" + $(this).val()).show();
});

Upvotes: 1

Alen
Alen

Reputation: 917

You can try something like this

if( "#" + $(this).val() == 'form_1' ){
    $("#form_1").show();
    $("#form_2").hide();
}
else {
    $("#form_1").hide();
    $("#form_2").show();
}

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Select all the forms in your dom and exclude the form to be shown, and hide it. Then show the form to be shown.

Try,

$("select").on("change", function() {    
  $('form').not("#" + $(this).val()).hide();
  $("#" + $(this).val()).show();
});

Upvotes: 2

Related Questions