Search code examples
javascriptjquerytwitter-bootstrapbootstrap-selectpicker

selected text to display in input box using jquery


I have a multiple select dropdown using selectpicker and i want to display the selected text in another input box with @selected name not the value. enter image description here In this on click of plus a dropdown should open and after selecting the plus remains but the selected text has to display in another input box. here is the code that i have tried HTML code

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script> 


 <select id='recruiter' name="recruiter"  class="selectpicker" multiple>
     <optgroup label="Camping">
    <option value="1">Tent</option>
    <option value="2">Flashlight</option>
    <option value="3">Toilet Paper</option>
  </optgroup>
    <optgroup label="fruits">
    <option value="6">apple</option>
    <option value="7">orange</option>
    <option value="8">banana</option>
  </optgroup>
  </select>
 <input type="text" class="width-100 chat-borderTB pad-5" placeholder="comment" aria-describedby="sizing-addon2" name="msg" id="msg">


  <script type="text/javascript">
         $("#recruiter").on("change",function(){

           update();
         });

         function update() {

var selected=[];
 $('#recruiter :selected').each(function(){
     selected[$(this).val()]=$(this).text();
    });
 // alert($.trim(selected));
console.log(selected);
         $("#msg").val(selected);
         }
      </script>

Can u suggest how to do this.


Solution

  • Try this code:

    var selected=[];
     $('#recruiter option:selected').each(function(){
         selected[$(this).val()]=$.trim($(this).text());
        });
    console.log(selected);
             $("#msg").val(selected);
             }