odedta
odedta

Reputation: 2478

Bootstrap Select plugin: deselect issue

I am using Bootstrap framework with the Bootstrap Select plugin.

This is a regular select tag, not multiple, here is the code I used:

<select class="selectpicker show-tick" name="main_course_select" id="main_course_select" title="main" data-style="btn-primary" data-width="100%">
    <?php echo get_food($mysqli,'main'); ?>
</select>

Where get_food() function simply prints <option> tags with values from the MySQLi database.

When I first click an option I can see it is ticked just fine, when I click the same option again I want the option to be deselected, why is this not a default feature is beyond me and I don't like to use multiple select to achieve this. Anyone have any idea on how to get this done?

Here is the problem reproduced:

$(document).ready(function() {
	$('.selectpicker').selectpicker();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/js/bootstrap-select.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/css/bootstrap-select.css">

<select class="selectpicker show-tick" name="main_course_select" id="main_course_select" title="main" data-style="btn-primary" data-width="100%">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

Upvotes: 1

Views: 248

Answers (1)

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

The only way to deselect is adding an empty option at first node.

<select class="selectpicker show-tick" name="main_course_select" id="main_course_select" title="main" data-style="btn-primary" data-width="100%">
    <option></option>
    <?php echo get_food($mysqli,'main'); ?>
</select>

By selecting empty option you are deselecting last choice. Some plugins like jquery chosen or jquery select2 do this trick to add the deselecting simple-value option.

Good luck

Upvotes: 1

Related Questions