DreamTeK
DreamTeK

Reputation: 34177

How to populate a dropdown select box by matching contained text?

I have created two identical dropdown select boxes as below:

HTML

<select id="ddl1" name="ddl1">
    <option value="1">TEXT 1</option>
    <option value="2">TEXT 2</option>
    <option value="3">TEXT 3</option>
</select>

<select id="ddl2" name="ddl2">
    <option value="1">TEXT 1</option>
    <option value="2">TEXT 2</option>
    <option value="3">TEXT 3</option>
</select>

Using jquery I have created code to update the value of one when the other changes and vice versa as below:

JQUERY

var a = ('#ddl1'),
    b = ('#ddl2');

$(a + ',' + b).change(selectddl);
$(selectddl);

function selectddl() {
    var val = $(this).val();
    var text = $(this).text();

    if (this.id === 'ddl1') {
        $(b + ' option[value="' + val + '"]').prop('selected', true);
        $(b).selectmenu('refresh');
    } else if (this.id === 'ddl2') {
        $(a + ' option[value="' + val + '"]').prop('selected', true);
        $(a).selectmenu('refresh');
    }
};

My requirements now are to update the select boxes based on their contained TEXT and not their value.


QUESTION

How to update a dropdown select box based on another select box contained TEXT?

After some research I have tried but failed to do this as below:

JQUERY

var a = ('#ddl1'),
    b = ('#ddl2');

$(a + ',' + b).change(selectddl);
$(selectddl);

function selectddl() {
    var val = $(this).val();
    var text = $(this).text();

    if (this.id === 'ddl1') {
        $(b + ' option[value="' + val + '"]').prop('selected', true);
        $(b).selectmenu('refresh');
    } else if (this.id === 'ddl2') {
        $(a + ' option:contains("' + text + '")').prop('selected', true);
        $(a).selectmenu('refresh');
    }
};

CLICK FOR DEMO

Can anyone explain how this can be achieved?

The correct answer to this question would NOT use contains due to the conflicts that could arise with text such as:

Upvotes: 1

Views: 1425

Answers (1)

Nate Kibler
Nate Kibler

Reputation: 652

You can use the .filter() function to achieve what you are requesting. You will basically need to select all of the options, then call .filter(), passing in a function that only accepts the option who's text is equal to what you expect.

For example, your else if statement might look like this:

else if (this.id === 'ddl2') {
    $(a + ' option').filter(function() {
        return this.text === text;
    }).prop('selected', true);
    $(a).selectmenu('refresh');
}

Also, it looks like you need to change your text variable as well. You should change it to something that will select the text of the currently selection option, like so:

var text = $(this).find(':selected').text();

Here's a working Fiddle.

Upvotes: 2

Related Questions