22

I'm trying to get the selected text, not value, from my bootstrap drop down, but my .text() statement is returning a string that contains all the values with a '\n' in between.

Here is my rendered html

<select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
    <option selected="selected" value="0">1-4</option>
    <option value="1">5-9</option>
    <option value="2">10-15</option>
    <option value="3">16-20</option>
    <option value="4">20+</option>
</select>

Here is my javascript, but selectedText returns '5-9\n10-15\n16-20\n20+' I want it to return 5-9 or 10-15, etc..

$('#SpaceAccommodation').change(function () {

    var selectedText = $(this).text();
});
Gary Kerr
  • 13,650
  • 4
  • 48
  • 51
chuckd
  • 13,460
  • 29
  • 152
  • 331

3 Answers3

45

You can get the selected value's text with $(this).find("option:selected").text().

$('#SpaceAccommodation').change(function () {
    var selectedText = $(this).find("option:selected").text();
    
    $(".test").text(selectedText);
});
<script src="https://code.jquery.com/jquery-1.6.4.min.js"></script>
<select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
    <option selected="selected" value="0">1-4</option>
    <option value="1">5-9</option>
    <option value="2">10-15</option>
    <option value="3">16-20</option>
    <option value="4">20+</option>
</select>
<div class="test"></div>
Nick Bartlett
  • 4,865
  • 2
  • 24
  • 37
6

Fiddle for you

 $(document).ready(function () {
     $('.chzn-select').change(function () {
         alert( $('.chzn-select option:selected').text());
     });
 });

<select id="second" class="chzn-select" style="width: 100px">
    <option value="1">one</option>
    <option value="2">two</option>
</select>

This is based on the css3 psuedo-class :selected. It's very similar to :checked, I couldn't find docs for :selected

J-Dizzle
  • 3,176
  • 6
  • 31
  • 49
1

In case anyone cares, I've got another solution. I just looked at the arguments from the docs. You can do something like this (Assuming you've set the value tag of the option element.:

 $('#type_dropdown')
                .on('changed.bs.select',
                    function(e, clickedIndex, newValue, oldValue) {
                        alert(e.target.value);
                    });
        });

See https://silviomoreto.github.io/bootstrap-select/options/

coolboyjules
  • 2,300
  • 4
  • 22
  • 42