Here's my code :
HTML :
<Select id="colorselector">
<option value="red-1">Red</option>
<option value="yellow-2">Yellow</option>
<option value="blue-2">Blue</option>
<option value="black-1">Black</option>
</Select>
<div id="-1" class="colors" style="display:none"> Div1... </div>
<div id="-2" class="colors" style="display:none"> Div2.. </div>
JS :
$(function() {
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
What I want : when I select an option that contains "-1"
the first div will appears, and the second div will disappear. And If I select an option that contains "-2"
the firs div will disappear, and the second one will appears.
Use split()
to get the number
$(function() { $('#colorselector').change(function() { $('.colors').hide(); $('#-' + $(this).val().split('-')[1]).show(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <Select id="colorselector"> <option value="red-1">Red</option> <option value="yellow-2">Yellow</option> <option value="blue-2">Blue</option> <option value="black-1">Black</option> </Select> <div id="-1" class="colors" style="display:none">Div1...</div> <div id="-2" class="colors" style="display:none">Div2..</div>
Try this:
JS:
$("#colorselector").change(function(){
if((this.options[this.selectedIndex].value).indexOf("-1") > -1) {
$("#-2").hide();
$("#-1").show();
}
else {
$("#-1").hide();
$("#-2").show();
}
});
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.