Reputation: 4266
I have the following code to toggle a variable DIV:
$('#'+content_id).toggle(option.hasClass(show_class));
I have tried to get the variable ID by concatenating the selected value and the names of the DIVs into one string. Either I'm not naming the variable correctly or am putting the variable in the wrong place.
Full code as follows:
HTML
<select name="select_name" id="select_id" class="select_class" data-inline="true">
<option class="show1" value="1">1</option>
<option class="show2" value="2">2</option>
<option class="show3" value="3">3</option>
<option class="show4" value="4">4</option>
</select>
<div id="content1">Div 1</div>
<div id="content2">Div 2</div>
<div id="content3">Div 3</div>
<div id="content4">Div 4</div>
<div id="testdiv"></div>
<div id="testdiv2"></div>
<div id="testdiv3"></div>
JS
$(function() {
$('#select_id').change(function() {
var option = $(this).find('option:selected');
var OptVal = document.getElementById('select_id').value;
document.getElementById("testdiv").innerHTML = OptVal;
var show_class = "show" + OptVal;
document.getElementById("testdiv2").innerHTML = show_class;
var content_id = "content" + OptVal;
document.getElementById("testdiv3").innerHTML = content_id;
$('#'+content_id).toggle(option.hasClass(show_class));
}).change();
});
Upvotes: 0
Views: 146
Reputation: 1368
I'm guessing that you want to only show the div for the selected option in the dropdown.
Here is your html:
<select name="select_name" id="select_id" class="select_class" data-inline="true">
<option class="show1" value="1">1</option>
<option class="show2" value="2">2</option>
<option class="show3" value="3">3</option>
<option class="show4" value="4">4</option>
</select>
<div id="content1" class="content">Div 1</div>
<div id="content2" class="content">Div 2</div>
<div id="content3" class="content">Div 3</div>
<div id="content4" class="content">Div 4</div>
<div id="testdiv"></div>
<div id="testdiv2"></div>
<div id="testdiv3"></div>
I added a content class to the divs to easily select all of them.
JavaScript:
$(function () {
$('#select_id').change(function () {
var option = $(this).find('option:selected');
var OptVal = document.getElementById('select_id').value;
document.getElementById("testdiv").innerHTML = OptVal;
var show_class = "show" + OptVal;
document.getElementById("testdiv2").innerHTML = show_class;
var content_id = "content" + OptVal;
document.getElementById("testdiv3").innerHTML = content_id;
$('.content').hide();
$('#' + content_id).show();
}).change();
});
I added the $('.content').hide();
to hide all of the divs and then I used $('#' + content_id).show();
to show the selected div.
Here is a working Fiddle: http://jsfiddle.net/JYbq2/
Upvotes: 1