March 25, 2012

Get option value depending on other element

Question by user1254282

I have the following html markup:

<div class="wrap_select">
    <span class="select" id="selectdateRange">Today, 25 March, Sun</span>
    <select class="styled" id="dateRange" name="dateRange">
        <option value="25.03.2012">Today, 25 March, Sun</option> // "current"
        <option value="26.03.2012">Tomorrow, 26 March, Fr</option>
        <option value="27.03.2012">27 March, Tu</option>
        <option value="28.03.2012">28 March, We</option>
        <option value="29.03.2012">29 March, Th</option>
    </select>
</div>

The <span class="select"> contain text from select options.
How can I get value of the “current” select?

For marup above the result must be 25.03.2012.

Answer by gdoron

var text = $.trim($('#selectdateRange').text());
var theWinner = $('select option').filter(function() {
    return $(this).text() == text;
}).val();

alert(theWinner);


LIVE DEMO

Answer by Starx

Here is an alternative way that does what you want

function findCurrent() {
    var currentText = $('span').text();
    var currentVal;
    $("select option").each(function(k,v) {
       if($(this).text()==currentText) {
           currentVal = $(this).val();
           return false;
       }
    });
    return currentVal;
}
// Usage
console.log(findCurrent());

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!