2

I am creating an select like this:

<select id="teamNameLabel" data-corners="false" onchange="GetSelectedTeam()" data-bind="options: teams, optionsText: 'name', optionsValue: 'id'">
    <option value="1">Select a Team...</option>
</select>

My application is a single page, so when an option is selected it is assigned to TeamId like this:

TeamId = $('#teamNameLabel').val();

I would like the selected option to be what was last selected when you navigate back to this page. I tested it with this when the page loaded, but the alert keeps coming back as undefined.

$("#teamNamelabel option").eq(TeamId+1).attr("selected","selected");
alert($("teamNameLabel option:selected").val());

Is there anyway i can set the selectedOption or .attr(selected) to be TeamId?

4

1 回答 1

8

You are missing # in that selector inside your alert and also you can just

alert($("#teamNameLabel").val());

instead of

alert($("#teamNameLabel option:selected").val());

And to set the value.. simply use .val again like below,

$("#teamNameLabel").val(TeamId);

You can use .eq selector when you need to select an option without knowing its value.

Assume you want to select 3rd option, then

//             3rd option = 2 because .eq takes index
$("#teamNamelabel option").eq(2).prop("selected", true);
于 2012-11-05T19:59:32.767 回答