Reputation: 605
I'm having trouble setting my selects to some default values that come in through ajax
Here's a fiddle: http://jsfiddle.net/helto/wycLZ/
Here's the code:
HTML:
<div>
<label id="conditionLabel" for="condition">Condition:</label>
<select id="condition">
<option selected="true" style="display:none;">Choose</option>
</select>
</div>
JS:
var conditions = [{
id: 1,
name: "New"
}, {
id: 2,
name: "Good"
}, {
id: 3,
name: "Poor"
}];
$.each(conditions, function (key, value) {
var cond = '<option value="' + value.id + '">' + value.name + '</option>';
$('#condition').append(cond);
});
$('#condition option[text="New"]').attr('selected', 'selected');
Its this last line that's giving me trouble, I want to select the option based on the text
Upvotes: 0
Views: 61
Reputation: 82327
You should use $('#condition option:contains("New")').prop('selected', true);
which takes advantage of jQuery's :contains() Selector
Here is a jsFiddle demo
Upvotes: 0
Reputation: 298492
You could use :contains
:
$('#condition option:contains("New")').prop('selected', true);
Or .filter()
:
$('#condition option').filter(function() {
return this.text === 'New';
}).prop('selected', true);
:contains
will match News
as well, so I'd go with .filter()
Upvotes: 3