取得 select 目前選中項的 value 與顯示文字,是表單處理裡非常基本的需求。
選擇時間段: <select name="timespan" id="timespan" class="Wdate"> <option value="1">8:00-8:30</option> <option value="2">8:30-9:00</option> <option value="3">9:00-9:30</option> </select>
var obj = $("#timespan option:selected");
var artime_val = obj.val();
var artime_text = obj.text();
alert("val: " + artime_val + " text: " + artime_text);
// val: 3 text: 9:00-9:30
關鍵是 option:selected 這個選擇器,它只會命中目前被選中的那一個 option;接著用 val() 取 value、用 text() 取顯示文字。
如果是 multiple 的多選 select,:selected 會命中多個元素,這時要搭配 each 遍歷:
$("#timespan option:selected").each(function () {
console.log($(this).val(), $(this).text());
});
另外補充一個常用寫法:直接對 select 本身取值也可以,寫成 $(\"#timespan\").val(),它會回傳選中項的 value(多選時回傳陣列)。若只想拿文字,則仍需透過 option:selected 繞一下。