I’m getting very wierd behavior when I empty a div then append another div to it using selected based on selected option. Hard to explain. When you select and option it works, but when you come back and select the same optiongroup again, it stops working completely. Please have a look at his example: http://jsbin.com/akeboz/3/
It’s probably me doing it tha wrong way again 😛 but what do you think is wrong with it?
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
<script>
$(document).ready(function(){
$('#carSelect').change(function(){
currentBrand = $(this).find('option:selected').data('brand');
$('#carContainer').empty();
$('#car_'+currentBrand).show().appendTo('#carContainer');
});
});
</script>
</head>
<body>
<form>
<select id="carSelect">
<optgroup label="Swedish Cars">
<option data-brand='volvo' value="volvo">Volvo</option>
<option data-brand='saab' value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars">
<option data-brand='mercedes' value="mercedes">Mercedes</option>
<option data-brand='audi' value="audi">Audi</option>
</optgroup>
</select>
<div id="carContainer"></div>
</form>
<div style="display:none;">
<div id="car_audi">
audi stuff
</div>
<div id="car_mercedes">
mercedes stuff
</div>
</div>
</body>
</html>
You’re appending, but then destroying what you appended when something else is selected, so there’s no way to get it back.
You want to make a clone of it, and append the clone.
Also, the
.show()isn’t needed because it is their parent that is hidden, not the elements themselves.Ultimately, I think it would be better to have the content nested in each car type, and put it back when you’re done with it (before grabbing the new content).
That way you’re not constantly destroying and rebuilding DOM elements.
Like this:
Then this: