Reputation: 4803
I'm sure this is relatively easy and straightforward, but I'm having no success figuring it out.
I am trying to set the selected option of a drop down list element using the following code:
if ($(this).attr("tagName") == "SELECT") {
oldValue = $(this).parent().parent().find('span.displayField').text();
$(this).val(oldValue).attr("selected", "selected");
return;
}
But it is not changing the select element at all. The code is definitely running, and oldValue
is being populated appropriately.
Can anyone see what I might be missing?
Thanks!
UPDATE:
For clarification, here is the HTML:
<span class="displayField">Pending</span>
<span class="editField">
<select data-val="true" data-val-number="The field ProgramStatusId must be a number." data-val-required="The ProgramStatusId field is required." id="ProgramListViewModels_0__ProgramStatusId" name="ProgramListViewModels[0].ProgramStatusId">
<option value="1">Pending</option>
<option value="2">Tabled</option>
<option value="3">Approved</option>
<option value="4">Declined</option>
</select>
</span>
Upvotes: 2
Views: 1108
Reputation: 227200
$(this).val(oldValue)
will set the value of this
to oldValue
, and you just wanna find options with that texy. You want to use :contains()
for this.
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option:contains('+oldValue+')', this).attr("selected", "selected");
return;
}
Or if there are multiple options that contain the text, but are different, try this:
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option', this).filter(function(){
return this.text === oldValue;
}).attr("selected", "selected");
return;
}
Upvotes: 2
Reputation: 9003
If I Understand your snippet correctly. I believe what you're trying to do is select the item with the same text()
as $('span.displayField')
.
if ($(this).attr('tagName') == 'SELECT') {
// unselect previously selected element first.
var prev = $(this).find('option:selected').attr('selected', false);
// select item with text from span.displayField
var oldText = $(this).parent().parent().find('span.displayField').text();
var oldOption = $(this).find('option[text="' + oldText + '"]');
oldOption.attr('selected', true);
}
Upvotes: 1
Reputation: 12417
I dont understand what is that
).parent().parent().
if you just want to set select box value selected try these
$('select.foo option:selected').val(); // get the value from a dropdown select
$('select.foo').val(); // get the value from a dropdown select
Upvotes: 0