Get value from "Bootstrap-Select"

I have a selectbox, and when I select a parameter, it updates the input field with selectbox values. This works with the old version of Bootstrap-Select. But in the new version, it no longer works. I am looking for a way to make this work in the new version. Thanks.

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();
+6
source share
2 answers

One solution is to use the methods Array.from()and mapfor all 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">
Run codeHide result

, arrow.

$('.ChangeCategory').val(Array.from($( ".Categoria option:selected" )).map(a=>$(a).text()).join(','));
+5

f2 :

var f2 = function(){
$('.ChangeCategory').val($( ".Categoria option:selected" ).text());
}
+1

Source: https://habr.com/ru/post/1016632/


All Articles