Hagbard Hagbard - 11 months ago 64
jQuery Question

How to return text values from Bootstrap Multi-Select

I'm using bootstrap select for a multiple enabled dropdown.
When a button is pressed i'm building a variable to use in an AJAX request.

It works for returning the values (basically the ID's in this case), since it returns an array of values, i can use a loop to build the JSON. However i also need to send the text value, but havent been able to get this working.

$('#sendButton').click(function() {
var modal = $('#modalPopup');
var modalID = modal.data('value');
var selectedOptionValue = $('#multiSelectBox').val();
var selectedOptionName = $('#multiSelectBox').text();
var sendRequest = {
'modalNo': modalID,
'products': []
for (var i = 0; i < selectedOptionValue.length; i++) {
'productId': selectedOptionValue[i],
'productName': selectedOptionName

I tried another loop to do
when building the request but no luck, i end up getting all of the text values in my drop down. Tried using:

var selectedOptionName = $('#multiSelectBox:selected').text();

But this doesn't return anything. Any ideas?

HTML for drop down:

<select class="selectpicker" multiple id="multiSelectBox" title="Select Product(s)"></select>

Code to populate dropdown:

var html = '';
for (var i = 0; i < data.products.length; i++){
html += '<option value ="' + data.products[i].productId+ '">' + data.products[i].productName+ '</option>'

Answer Source

The correct syntax is

$("#multiSelectBox option:selected").text()

but this will give you a string of all selected text. So you need to find the text by value in your loop.I didn't check for syntax here, there might be typos.

for (var i = 0; i < selectedOptionValue.length; i++) {

var val = selectedOptionValue[i]; 
var txt = $("#multiSelectBox option[value='"+val+"']").text();

            'productId': val ,
            'productName': txt