2

I got new javascript library or plugins right now and I love it, so cool and so easy to use. This is bootstrap-select by Silvio Moreto. But now I'm looking for a way to create, add, or append new option on a select when I'm using live search if "No search match".

The same at https://www.electrictoolbox.com/javascript-add-options-html-select/ but little different I want the button are inside the search box and it can save into the database

I'm using the following codes below:

$('.selectpicker').selectpicker({
    style: 'btn-default',
    width:'100%'
 });
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
  
 <select class="selectpicker" data-live-search="true" >
   <option data-tokens="Hotdog" value="Hotdog">Hot Dog</option>
   <option data-tokens="Burger" value="Burger">Burger</option>
   <option data-tokens="Sugar" value="Sugar">Sugar</option>
   <option data-tokens="Donut" value="Sugar">Donut</option>
</select>

I'm imagine this:

enter image description here

1 Answers1

6

this will led you to your desired result,apply css on your own,might help you

$("#tags").select2({
  tags: true,
  createTag: function (params) {
    return {
      id: params.term,
      text: params.term,
      newOption: true
    }
  },
   templateResult: function (data) {
    var $result = $("<span></span>");

    $result.text(data.text);

    if (data.newOption) {
      $result.append(" <em>(new)</em>");
    }

    return $result;
  }
});
#tags
{
  width: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>

<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>

<select id='tags'>
<option value="test">Test</option>
</select>
this.girish
  • 1,296
  • 14
  • 17
  • How does it save to the database without refreshing a page? And how do I add another option?@this girish –  May 05 '17 at 06:30