2
votes

I am using bootstrap select dropdown which has the following code.

HTML


    @Html.DropDownList("Product", SelectList, new { data_live_search = "true", @class = "content-small selectpicker", @tabindex = 1 })

In this dropdown i need to provide an option to add new values which are typed in the search bar in the dropdown to the existing collection of the dropdown based on the click event. I have modified the UI to say "Create" instead of No results found. Please refer the code and UI below.

JS


    $('#Product').selectpicker({ noneResultsText: 'Create ' });

UI

UI for Create option

I am trying to add click event to this text "Create" content which is highlighted in the screenshot above to add that content dynamically to the existing collection of the dropdown.

But, while clicking that text the dropdown gets closed and the element which shows the text gets removed, hence i could not call the on click function to add this item dynamically.

Can anyone please let me know the possibilities of using this.?

Vijay.

1
theoretically, there should be an array of options and you will use the find() or filter() method to find the typed value, in case nothing matches you can return button div from some function. the button can be an html div with click event enabled. if you interested, i can explain. - Ali Waqas
@AliWaqas can get the typed value from the search box of the dropdown. But, i need to process the typed value only when the user clicks the "Create "typed text"" value. Since i cannot use the click event because the dropdown gets closed on its click. - Vijay457

1 Answers

0
votes

I think you're skipping that the input you're dealing with is outside of the .selectpicker. You can find working snippet below.

$('.selectpicker').selectpicker({
  noneResultsText: '<a href="#" class="creator">Create</a> '
});

$(".selectpicker").on("click",".creator",function(){
    $("p span").html("Clicked for "+$(".pickercontainer .bs-searchbox input").val());
});
.creator {
  display:inline-block;
  float:left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" />
<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>


<div class='pickercontainer'>
  <select class="selectpicker" data-live-search="true" >  
    <option>Alabama</option>
    <option>Alaska </option>
    <option>Arizona </option>   
  </select>
</div>
<br>

<p>Action: <span></span></p>