I am trying to make a select2 search box visible if the values in a HTML drodown match a value. Following is my code snippet.
Somehow, the Select2 dropdown is always shown.
Any help is appreciated...
I have added the CSS based on the suggestion on select2 github repo https://github.com/select2/select2/issues/861
<html>
<style type="text/css">
.other {
display: none !important;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="one" name="one" id="one">
<option value="1">1</option>
<option value="2">3</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<br>
<br>
<select class="other" name="other" multiple="multiple">
<option value="AL">Sample1</option>
<option value="WY">Sample2</option>
</select>
<script>
// In your Javascript (external .js resource or <script> tag)
$("#one").change(function() {
$('#value').change(function()
{
if($('#value').val() == '1')
{
$('.other').hide();
} else
{
$('.other').show();
}
}
)});
$(document).ready(function() {
$(".other").select2({
tags: true
});
});
</script>
</html>
Can you do something like this ? Not sure about your usercase. But I will suggest to destroy the select and then hide. And later again create the instance and show.
$("#one").change(function() {
if($(this).val() == '3')
{
$('.other').select2('destroy');
$('.other').hide();
} else {
$(".other").select2({
tags: true
});
$('.other').show();
}
});
$(document).ready(function() {
$(".other").select2({
tags: true
});
});
<html>
<style type="text/css">
.other {
display: none !important;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="one" name="one" id="one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<br>
<br>
<select class="other" name="other" multiple="multiple" style="width: 100px;">
<option value="AL">Sample1</option>
<option value="WY">Sample2</option>
</select>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With