Reputation: 8146
I am trying to display div on change of select option change.
I have get data of each selected option on change but I want to display that name div on change of select item.
when I click on option that will show that div and when i ll change select item then it ll change div and above display div will invisible.
code :
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
alert(str);
$( ".mobile" ).show();
})
.change();
what I will have to use on $( ".mobile" ).show();
line ?
I have tried $( .str ).show();
but not working.
i want to change div on select change.
I have displayed alert box that will show text of option selected.
Any suggestion please.
Upvotes: 0
Views: 4761
Reputation: 15636
Markup:
<select name="sweets">
<option value="1">laptop</option>
<option value="2">mobile</option>
<option value="3">shoes</option>
<option value="4">watch</option>
<option value="5">tablet</option>
<option value="6">shirt</option>
</select>
<br>
<div class="device laptop" style="position: absolute;z-index: 1;">laptop</div>
<div class="device mobile" style="position: absolute;z-index: 1;">mobile</div>
<div class="device shoes" style="position: absolute;z-index: 1;">shoes</div>
Script:
$("select")
.change(function () {
var str = $("select option:selected").text();
$(".device").hide();
$("." + str).show();
})
Upvotes: 2
Reputation: 44740
You can make it work like this -
$("select").change(function () {
$('div').hide();
$('.'+$('option:selected',this).text()).show();
}).change();
Demo ----->
http://jsfiddle.net/nCRh6/7/
Upvotes: 0
Reputation: 15891
change this $( ".mobile" ).show();
to this = > $("."+str).show();
since you have hard-coded your jQ to .mobile
, it is not changing!! :)
So final jQ is
$("select")
.change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
alert(str);
$("."+str).show(); /* changed here*/
})
.change();
EDIT
for that you can use
$( "div:visible" ).hide();
Upvotes: 1
Reputation: 4525
You can do this:
$('div').hide();
$( "." + str).show();
Fiddle: Demo
Upvotes: 0
Reputation: 74738
You can change this:
$( ".mobile" ).show();
to this:
$("."+str).show().siblings('div').hide();
Upvotes: 0