Search code examples
jquerybootstrap-selectpicker

Get selected option text from select piker and append it to div on click


I have used select picker for creating city dropdown list. Now I am doing an exercise in which I have to get that selected option text and append it to the div without the comma(,).

If I have Selected

City1, City4, City5

Here is my select piker code:

<select class="selectpicker citySelectPiker" name="city" id="city" multiple data-style="btn-white" data-live-search="true">
    <option value="1">City1</option>
    <option value="2">City2</option>
    <option value="3">City3</option>
    <option value="4">City4</option>
    <option value="5">City5</option>
</select>

Now on click I want that selected text inside div something like this:

<div id="job_desc_preview">
   <button class="btn btn-primary waves-effect waves-light btn-xs">City1</button>
   <button class="btn btn-primary waves-effect waves-light btn-xs">City4</button>
   <button class="btn btn-primary waves-effect waves-light btn-xs">City5</button>
</div>

I have Tried This Script:

 var city_string = $('.citySelectPiker').find('.filter-option').text();

Basically, I want that comma separated string's each element in different div.

Here is the Div on it clicks I want that comma separated string to placed in div.

<button type="button" class="btn btn-info waves-effect" id="previewButton">Preview</button>

Required Output.

On this button click Want to get the selected(citySelectPiker) values and want to place that inside (job_desc_preview) div.


Solution

  • For adding a value in the div from comma separated string.

    First Create String:

    $('.citySelectPiker').change(function() {
      var selectedText = $(this).find('option:selected').map(function() {
        return $(this).text();
      }).get().join(',');
    
      console.log(selectedText);
    });
    

    Now Split that string to an array.

    var city_array = selectedText.split(',');
    

    Now, Add that array value in the div.

    $('#previewButton').click(function () {
        for (i = 0; i < city_array.length; i++) {       
            '<button class="btn btn-primary waves-effect waves-light btn-xs">' + city_array[i] + '</button>;';        
        }
    });