tags:

views:

65

answers:

4

In jquery 1.3.2, the following works:

<select id="c">
  <option value="325">Red</option>
  <option value="833">Purple</option>
</select>

$('#c').val('Red');

And it changes the select to the option with RED as its label. In jQuery 1.4 this fails. How can I get the same result in 1.4? Was this a bug in the 1.3 version?

A: 

Try

$('#c').val("325");
rahul
+2  A: 
$('#c').val('Red');

shouldn't have (imho) worked in jQuery 1.3 because "Red" isn't the value. "325" is. What does this do:

$('#c').val("325");
cletus
Does work in 1.3.2, whysoever.
aefxx
Oh, I know what you put would make it work; but I dont have access, in this case, to the value, I have to set it by the label. My short term solution was to downgrade back to jQuery 1.3.2
Stomped
+2  A: 

You would have to do it this way:

$('option:contains("Red")', '#c')[0].selected = true

EDIT

@Tomalak

If the labels arent mutually exclusivey you'd need to rewrite the selector:

$.fn.labselect = function(str) {
    $('option', this).filter(function() {
       return $(this).text() == str;
    })[0].selected = true;

    return this;
};

// Use it like this
$('#c').labselect('Red');
aefxx
What about `<option>InfraRed</option>`?
Tomalak
+1 now. I don't see a reason for limiting it to `<option>` elements, the filter function could work on all elements. You could call it `textfilter()` and remove the `selected = true`. Selecting should be in the "use it like this" part.
Tomalak
My question wasn't specific enough, but you answered it anyway, I do need to select via the label, so the custom function is the way to go.
Stomped
@Tomalak `textfilter` wouldn't make much sense imho. If one needs that kind of filtering, I would go with your approach extending the selector engine as its the jQuery way of doing things.
aefxx
+1  A: 
$('#c').val('325');

or

// earlier - define a text-equals selector
jQuery.extend(jQuery.expr[":"], {
  "text-equals": function (a, i, m) {
    return (a.textContent||a.innerText||jQuery(a).text()||'')==m[3];
  }
});

// later - use it
$red = $('#c option:text-equals(Red)');
$('#c').val($red.val());

The custom selector is one possibility. You could also do exactly the same thing in a filter() callback, for example.

Tomalak