これらの解決策は、ドロップダウン リスト内の各項目に、ドロップダウン リスト内の位置に関連するval()値があることを前提としているようです。
そうでない場合、事態はもう少し複雑になります。
ドロップダウン リストの選択されたインデックスを読み取るには、次のようにします。
$("#dropDownList").prop("selectedIndex");
ドロップダウン リストの選択されたインデックスを設定するには、次のようにします。
$("#dropDownList").prop("selectedIndex", 1);
prop()機能には JQuery v1.6 以降が必要であることに注意してください。
これら 2 つの関数をどのように使用するか見てみましょう。
月名のドロップダウン リストがあるとします。
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
現在選択されているドロップダウンリスト項目を見て、前月/翌月に変更する「前月」および「次月」ボタンを追加できます。
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
これらのボタンが実行する JavaScript は次のとおりです。
function btnPrevMonth_Click() {
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
if (selectedIndex > 0) {
$("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
}
}
function btnNextMonth_Click() {
// Note: the JQuery "prop" function requires JQuery v1.6 or later
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
var itemsInDropDownList = $("#listOfMonths option").length;
// If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
if (selectedIndex < (itemsInDropDownList - 1)) {
$("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
}
}
私のサイトは、ドロップダウン リストに JSON データを入力する方法を示すのにも役立ちます。
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm