I have drop down select and show hide other fields (within divs) based on option selected in the dropdown list.
This code works fine and show hide based on selection but
Assign an common class to all the div's that holds the content
show hide based on selection but when I load the page all fields are visible
<div id="row1_col1_layout_type2" class="content">
^
----- This to target with a single selector
CSS
.content{
display :none;
}
And in the JS just trigger the change event so as to show the div with option that is selected
$('#row1_layout_options').change(function() {
$('.content').hide();
$('#row1_col1_' + $(this).val()).show();
// Sen d an ajax request to save the value in DB
$.ajax({
});
}).change(); <--- Trigger the event
Next is the Page Reload. Web is stateless
. So it will not remember the previous state. The only thing you can do is persist the value after page refresh. Maybe in as a cookie, Local Storage or saving it on server and retrieving it back..
Check Fiddle
I would suggest adding a class for your loaded content which will make them hidden.
HTML
<select id="row1_layout_options" name="row1_layout_options">
<option value="Select Layout Type">Select Layout Type</option>
<option value="layout_type1">layout_type1</option>
<option value="layout_type2">layout_type2</option>
<option value="layout_type3">layout_type3</option>
<option value="layout_type4">layout_type4</option>
<option value="layout_type5">layout_type5</option>
<option value="layout_type6">layout_type6</option>
<option value="layout_type7">layout_type7</option>
<option value="layout_type8">layout_type8</option>
</select>
<div id="layouts">
<div id="row1_col1_layout_type2">
<input type="text" class="qa-form-tall-text" value="" name="q2am_fp_row1_col1_layout_type2">
</div>
</div>
JS
$('#row1_layout_options').change(function() {
$('#layouts>div.selected').removeClass('selected');
$('#row1_col1_' + $(this).val()).addClass('selected');
});
CSS
#layouts>div{
display:none;
}
#layouts>div.selected{
display:block;
}
EDIT : Saving selected
As for saving the selected option you have these non exhaustive list of solution :
localStorage
which is a javascript accessible store that is flushed like cookies. I wouldn't recommend that one I found it very much unreliable.selected
you send a query to a webservice that will save the state somewhere (DB, object instance etc...)http://localhost/mysite?selectedId=2
. This way you can have the information directly within the link. Easier to share the state.Just do the same in document.ready
$(document).ready(function(){
$('#row1_col1_layout_type1, #row1_col1_layout_type2, #row1_col1_layout_type3').hide();
$('#row1_col1_' + $('#row1_layout_options').val()).show();
$('#row1_layout_options').on('change',function() {
$('#row1_col1_layout_type1, #row1_col1_layout_type2, #row1_col1_layout_type3').hide();
$('#row1_col1_' + $(this).val()).show();
});
});
here is the fiddle