2

I'm trying to pull out the text from multiple select options, I've managed pull out the value for each with the following code, however when I use .text() I get all options text, rather than the one selected.

    $('#mySelects > .form-group select').each(function(){
            alert($(this).val());
    });

Here is a sample of the HTML:

    <div id="mySelects" class="panel-body">
        <div class="form-group">
           <select name="select-1" id="select-1" class="form-control">
         <option selected="selected" value="0">Please Select</option>
         <option value="11700599">Test Value 1</option>
           </select>
        </div>

        <div class="form-group">
           <select name="select-2" id="select-2" class="form-control">
         <option selected="selected" value="0">Please Select</option>
         <option value="11700467">Test Value 2</option>
           </select>
   </div>

My current jQuery will return: 0, 0 I want it to return: "Please Select", "Please Select" (or whatever text is selected)

1 Answer 1

6

That is because val(), when called on the <select> element, will return the value attribute of the selected children <option>. However, when you call .text() on $(this), you are fetching all text nodes within the entire <select> element itself. So, use this instead:

$('#mySelects > .form-group select').each(function(){
    var $optText = $(this).find('option:selected');
    alert($optText.text());
});

Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/7vvX7/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.