1

I have a very simple select with a custom options attribute:

    <select name='beverage' id='beverage'>
        <option value='0' desc='Tea'>Tea</option>
        <option value='1' desc='Coffee'>Coffee</option>
        <option value='2' desc= ‘Lemonade'>Lemonade</option>
    </select>

If I am passed a variable based on 'value', I can easily make the corresponding option "Selected" by thus:

    Var chosen = 1;
    $("#beverage").val( chosen ).attr('selected',true);

But if I am passed a var based on the 'desc' attr, like so:

    Var chosen = 'Coffee';

How do I make the selection? I have tried endless combinations like:

    ($("#beverage").attr( 'desc' = chosen )).attr('selected',true);

or

    ($("#beverage").attr( ['desc' = chosen] )).attr('selected',true);

and also tried using the filter option with no success. Very frustrating as I know this is a simple problem.

2 Answers2

1

You can use the attributes selector, but you have to target the option that has the attribute and not the select :

var chosen = 'Coffee';
$("#beverage option[desc='" + chosen + "']").prop('selected', true);

FIDDLE

Note that desc is not a valid attribute, and you should be using data-desc instead.

adeneo
  • 312,895
  • 29
  • 395
  • 388
0
$('#beverage[descr="chosen"]').attr('selected',true);