-2

I made many search but I can not solve my issue.

<select id="my_select">
    <option value="Findme_1">Knowing_1
    <option value="Findme_2">Knowing_2
</select>

In a function, I need to find the value of the option with "Findme_1" in content.

How can I do this please?

EDIT: I do not need to find the value of the selected option, I do not neither need to find the value of an option using its index, I only know the content "Knowing_1" and I want to know the value "Findme_1".

I thought about a loop but may be there are an other more common way?

Delgan
  • 16,542
  • 9
  • 83
  • 127

5 Answers5

0

Use this. example

   $('#my_select').find('option[text="Knowing_1"]').val()
NullPointerException
  • 3,607
  • 5
  • 23
  • 57
0

Use the SelectedIndex property. Check This

Buzz LIghtyear
  • 450
  • 5
  • 16
0

This will alert the value of the selected option:

(function() {

    var select = document.getElementById('my_select');
    select.addEventListener('change', function(){
        alert( select.options[select.selectedIndex].value );
    });

})();

Also, you should close your option elements:

<select id="my_select">
    <option value="Test_1">Findme_1</option>
    <option value="Test_2">Findme_2</option>
</select>

Full code and preview: http://jsfiddle.net/CX5aq/

chrx
  • 3,344
  • 1
  • 14
  • 17
0

First of all , your html is not correct, you are missing the close tag. It shuld be like this

<select id="my_select">
    <option value="Test_1">Findme_1 </option>
    <option value="Test_2">Findme_2 </option>
</select>

Then I guess, you are looking to get the value by javascript whenever user selects the dropdown so now write a javascript

<script> 
    document.getElementById('my_select').onchange = function(){

      var my_value = this.value; // you have your new value on the variable my_value

    }; 
</script> 
prabeen giri
  • 783
  • 6
  • 18
0

To find an <option> by its text, you can loop over the options collection and check textContent (standard) or innerText (IE, non-standard):

function valueByText(select, text) {
    var options = select.options;
    var textContent;

    for (var i = 0, l = options.length; i < l; i++) {
        textContent = options[i].textContent || options[i].innerText;

        if (textContent.indexOf(text) >= -1) {
            return options[i].value;
        }
    }

    return null;
}

var result = valueByText(document.getElementById('my_select'), 'Knowing_1');

Example: http://jsfiddle.net/jXpS2/


Also, if you have DOM library available to you, they can help simplify this.

Such as jQuery's :contains() selector:

var result = $('#my_select option:contains("Knowing_1")').val();

Example: http://jsfiddle.net/rcjfj/

Jonathan Lonowski
  • 117,332
  • 31
  • 195
  • 197