Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from "Bootstrap-Select"

I have a selectbox and when I select the option it updates the input box with the selectbox's values. This is working with an older version of Bootstrap-Select. But in the newer version it doesn't work anymore. I am looking for a way to make this to work in the newer version. Thanks.

  • Old version (working): http://jsfiddle.net/u967uwtf/
  • Newer version (not working): http://jsfiddle.net/9nzcLar6/

HTML:

<select class="selectpicker Categoria" multiple="">
  <option selected>A1</option>
  <option selected>A2</option>
  <option>A3</option>
  <option>A4</option>
</select>
<input type="text" class="ChangeCategory" name="ChangeCategory">

JS:

$('select').selectpicker();

$(".Categoria").change(function() {
  f2();
});

var f2 = function(){
  $('.ChangeCategory').val($(".Categoria").val());
}
f2();
like image 441
Khrys Avatar asked Apr 19 '17 13:04

Khrys


2 Answers

One solution is to use Array.from() and map methods in order to obtain all the selected values.

var values=Array.from($(".Categoria").find(':selected')).map(function(item){
    return $(item).text();
});

Working solution

$('select').selectpicker();

$(".Categoria").change(function() {
  f2();
});

var f2 = function(){
   var values=Array.from($(".Categoria").find(':selected')).map(function(item){
      return $(item).text();
   });
   $('.ChangeCategory').val(values);
}
f2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/><select class="selectpicker Categoria" multiple="">
    <option selected>A1</option>
    <option selected>A2</option>
    <option>A3</option>
    <option>A4</option>
</select>
<input type="text" class="ChangeCategory" name="ChangeCategory">

You can do this, also, in a single line of code, using arrow function.

$('.ChangeCategory').val(Array.from($( ".Categoria option:selected" )).map(a=>$(a).text()).join(','));
like image 51
Mihai Alexandru-Ionut Avatar answered Nov 18 '22 17:11

Mihai Alexandru-Ionut


replace f2 with below:

var f2 = function(){
$('.ChangeCategory').val($( ".Categoria option:selected" ).text());
}
like image 41
sai v Avatar answered Nov 18 '22 16:11

sai v