Reputation: 155
I have a dropdown list which has options- A,B,C,D. I want to hide other input fields based on the selection from dropdown.
I can successfully hide fields if user selects A. I dont know how to hide fields if user selects either A or B.
Working Code:
$('#lockForm select[name="Key"]').change(function () {
if ($('#lockForm select[name="Key"] option:selected').val() == 'A') {
$('.hidden').hide();
} else {
$('.hidden').show();
}
});
<form:form method="post" id="lockForm">
<div class="plselect">
<form:select path="Key">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${List}" itemValue="Code" itemLabel="Desc"/>
</form:select>
</div>
</form:form>
Upvotes: 0
Views: 99
Reputation: 9614
You can gain a full control by telling the script what elements to hide and what to show on option select. You can do it by adding data to option elements this way:
function showHide(e) {
var selectedOption = $(this).find('option:selected');
$( selectedOption.data('hide') ).hide();
$( selectedOption.data('show') ).show();
};
$('select')
.on('change', showHide)
.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<select>
<option data-hide=".user-input" data-show=".user-input-a" value="A">show A</option>
<option data-hide=".user-input" data-show=".user-input-b" value="B">show B</option>
<option data-hide=".user-input" data-show=".user-input-c" value="C">show C</option>
<option data-hide=".user-input" data-show=".user-input-d" value="D">show D</option>
<option data-hide=".user-input" data-show=".user-input-a,.user-input-d" value="AD">show A and D</option>
<option data-hide=".user-input" data-show="" value="">hide all</option>
<option data-hide="" data-show=".user-input" value="ABCD">show all</option>
</select>
</p>
<p class="user-input user-input-a">
A - any content
</p>
<p class="user-input user-input-b">
B - any content
</p>
<p class="user-input user-input-c">
C - any content
</p>
<p class="user-input user-input-d">
D - any content
</p>
This way you can use it on any select on your page, no need to change Javascript code any more, just add attributes in HTML.
Same code on Playground.
Upvotes: 1
Reputation: 1578
You could just make two checks in your if statement with an OR:
if ($('#lockForm select[name="Key"] option:selected').val() == 'A' || '#lockForm select[name="Key"] option:selected').val() == 'B' )
You could clean it up further by saying
var selectedOption = $('#lockForm select[name="Key"] option:selected').val();
...
if (selectedOption == 'A' || selectedOption == 'B' )
Upvotes: 0