I am trying to create a function where the div will show based on the select box option selection and the selected option will disappear, again if the div is hidden then the select box option will appear.
e.g in my code When I select Red Option then the div#red show();
When I click cancel('red') the div is disappeared as expected by it the select option for red is still removed, I want to reflect the same.
how I achieve the goal, help
<select id="colorselector">
<option value="0" selected>--</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</select>
<div id="red" style="display:none; color:red"> red...
<span><a onclick="cancel('red')">Cancel</a></span>
</div>
<div id="yellow" style="display:none; color:yellow"> yellow..
<span><a onclick="cancel('yellow')">Cancel</a></span>
</div>
<div id="blue" style="display:none; color:blue"> blue..
<span><a onclick="cancel('')">Cancel</a></span>
</div>
$(function() {
$('#colorselector').change(function() {
$('.colors').hide();
$('#' $(this).val()).show();
$('option:selected').remove();
});
});
function cancel(num) {
$("div#" num).remove();
}
CodePudding user response:
Your issue is that .remove()
deletes the html from the page - the only way to add it back would be to re-add the option (and the colour div).
Instead, use .hide()
and .show()
.
$(function() {
$('#colorselector').change(function() {
$('.colors').hide();
$("option").show();
$('#' $(this).val()).show();
$('option:selected').hide();
});
});
function cancel(num) {
$("div#" num).hide();
$('option').show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="colorselector">
<option value="0" selected>--</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</select>
<div id="red" style="display:none; color:red"> red...
<span><a onclick="cancel('red')">Cancel</a></span>
</div>
<div id="yellow" style="display:none; color:yellow"> yellow..
<span><a onclick="cancel('yellow')">Cancel</a></span>
</div>
<div id="blue" style="display:none; color:blue"> blue..
<span><a onclick="cancel('blue')">Cancel</a></span>
</div>