I use this script below for show or hidden a few <div>
. The selected
class in the script is associated with a display:block
and my <div>
start with a class with a display:none
.
When the page is load all div
are hidden. But I will like show the first of this, but I can do this?
$(document).ready(function(){
$("select[name*='material']").change(function(){
select_changed();
});
});
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
}
I have already set an option like first items, but this not show up. I think the problem is all div
in the begin have a display:none
class. How I can do.
For let more clear: HTML
<div class="materiali">
<select name="material" id="material">
<option value="mat-1">Material 1</option>
<option value="mat-2">Material 2</option>
</select>
</div>
<div class="boxx" id="mat-1">
Materail 1
</div>
<div class="boxx" id="mat-2">
Materail 2
</div>
CSS
.boxx{
display: none
}
.selected{
display: block;
}
Since you already have written a function for select_changed()
just invoke that function on ready function do as follows:
$(document).ready(function(){ $("select[name*='material']").change(function(){ select_changed(); }); select_changed() //here you can invoke your function on page ready }); function select_changed(){ $("div[id*='mat-']").each(function(){ $(this).removeClass('selected'); }); $("select[name*='material']").each(function(){ var selected = $(this).val(); $('#'+selected).addClass('selected'); }); }
.boxx{ display: none } .selected{ display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="materiali"> <select name="material" id="material"> <option value="mat-1">Material 1</option> <option value="mat-2">Material 2</option> </select> </div> <div class="boxx" id="mat-1"> Materail 1 </div> <div class="boxx" id="mat-2"> Materail 2 </div>
$(document).ready(function(){ function select_changed(){ $("div[id*='mat-']").each(function(){ $(this).removeClass('selected'); }); $("select[name*='material']").each(function(){ var selected = $(this).val(); $('#'+selected).addClass('selected'); }); }; $("select[name*='material']").change(function(){ select_changed(); }); $("select[name*='material']").change(); });
.boxx{ display: none } .selected{ display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="materiali"> <select name="material" id="material"> <option value="mat-1">Material 1</option> <option value="mat-2">Material 2</option> </select> </div> <div class="boxx" id="mat-1"> Materail 1</div><div class="boxx" id="mat-2">Materail 2</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.