I am working on this project that has a reservation form which allow users specify which sort of service they require. I have a select menu with eight (8) options and I have two divs which would either show/hide depending on the value of the option been selected. Seen below is the select element:
<select name="serviceChoice" id="serviceChoice">
<option value="A">Option A</option>
<option value="B">Option B</option>
<option value="C" selected="selected">Option C</option>
<option value="D">Option D</option>
<option value="E">Option E</option>
<option value="F">Option F</option>
</select>
<div id="field_1" class="optionBox">I have several form fields</div>
<div id="field_2" class="optionBox">I have several form fields</div>
I have written my jQuery code to alternate between these divs, however I would like to know if there is a shorter better way to get this done. I would also like to clear the values of any input elements in a div which has been hidden due to the choice of the user. My code is as follows:
(function($){
$('#field_1').show();
$('select[name=serviceChoice]').change(function(){
if( $('select[name=serviceChoice] option:selected').val() == 'A' ) {
$('.optionBox').hide();
$('#dropOff').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'B' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'C' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else if ( $('select[name=serviceChoice] option:selected').val() == 'D' ) {
$('.optionBox').hide();
$('#pickUp').show();
} else {
$('.optionBox').show();
}
});
})(jQuery);
1 Answer 1
// You can use the document.ready as both encapsulation as well as
// to make sure the DOM is ready for operation.
$(function ($) {
// Unless these are dynamic (the set could change), it's better to cache them
var optionBox = $('.optionBox');
var dropOff = $('#dropOff');
var pickUp = $('#pickUp');
var field1 = $('#field_1');
field.show();
// Your select box has an ID. They are faster than attribute selectors
// in both parsing ase well as fetching from the DOM
$('#serviceChoice').change(function () {
// The current context of this function is the DOM element, which is the select
// You can use it to get the value, rather than using a selector again. Removes
// the need for jQuery to parse the selector and look for it in the DOM
switch ($(this).val()) {
case 'A':
optionBox.hide();
dropOff.show();
break;
case 'B':
case 'C':
case 'D':
optionBox.hide();
pickUp.show();
break;
default:
optionBox.show();
}
});
});
Minus the comments, here's what you get:
$(function ($) {
var optionBox = $('.optionBox');
var dropOff = $('#dropOff');
var pickUp = $('#pickUp');
var field1 = $('#field_1');
field.show();
$('#serviceChoice').change(function () {
switch ($(this).val()) {
case 'A':
optionBox.hide();
dropOff.show();
break;
case 'B':
case 'C':
case 'D':
optionBox.hide();
pickUp.show();
break;
default:
optionBox.show()
}
})
});