Here is my html code:
<select id="myselect" class="selectpicker" data-live-search="true" placeholder="please type" data-live-Search-Placeholder="search">
<option value="111">AAAAAAAAAAA</option>
<option value="222">bbbbbbbbbbb</option>
<option value="333">cccccccccc</option>
</select>
Here is my javascript code:
$(function(){
var select1 = $('#myselect').selectpicker();
//var mysearchkeyword = $('#myselect').selectpicker('search.initiated').val();
//var mysearchkeyword = $('#myselect').selectpicker('search.input').val();
var mysearchkeyword = $('#myselect').selectpicker('.bs-searchbox').val();
select1.on('changed.bs.select', function (e) {
alert(mysearchkeyword);
});
})
Here is my fiddle: JSFiddle
I want to get the data of searchbox input in bootstrap-select. For example if I type "a" in searchbox I want it to get the "a" as alert message. I read this guide and tried a few ways but it didn't work. Can you please help me?
Thanks in advance.
Since the value will constantly change, I would create the variable as the actual element.
If you look at the DOM structure, you'll see that the div.bs-searchbox
element is a child of a sibling element to the $('#myselect')
element.
So, to get the div.bs-searchbox
element, first get the parent of the $('#myselect')
element, then use .find('.bs-searchbox > input')
to search it's dependents, to get the <input>
child of the div.bs-searchbox
element (remember that it is the input
element that has the value of the search, not the .bs-searchbox
div element).
Then on your event listener, just get the .val()
of your searchBoxElement
variable.
See snippet below
$(function() {
var select1 = $('#myselect').selectpicker();
//var mysearchkeyword = $('#myselect').selectpicker('search.initiated').val();
//var mysearchkeyword = $('#myselect').selectpicker('search.input').val();
//var mysearchkeyword = $('#myselect').selectpicker('.bs-searchbox').val();
var searchBoxElement = $('#myselect').parent().find('.bs-searchbox > input');
select1.on('changed.bs.select', function(e) {
alert(searchBoxElement.val());
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/css/bootstrap-select.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/js/bootstrap-select.min.js"></script>
<select id="myselect" class="selectpicker" data-live-search="true" placeholder="please type" data-live-Search-Placeholder="search">
<option value="111">AAAAAAAAAAA</option>
<option value="222">bbbbbbbbbbb</option>
<option value="333">cccccccccc</option>
</select>