下拉選單的操作逃不過增、刪、改、查這四件事。這裡把 jQuery 對 select 的常見寫法集中整理一份,之後要查也方便。文末另外附上一個日曆天數連動的實作。
$("#select_id").append("<option value='Value'>Text</option>"); // 在末尾追加一個選項
$("#select_id").prepend("<option value='0'>請選擇</option>"); // 插入到第一個位置
$("#select_id option:last").remove(); // 刪除索引最大的選項(最後一個)
$("#select_id option[index='0']").remove(); // 刪除索引為 0 的選項(第一個)
$("#select_id option[value='3']").remove(); // 刪除 value='3' 的選項
$("#select_id option[text='4']").remove(); // 刪除 text='4' 的選項
$("#select_id").empty(); // 全部清空
$("#select_id").get(0).selectedIndex = 1; // 選中索引為 1 的項
$("#select_id").val(4); // 選中 value 為 4 的項
$("#select_id option[text='jQuery']").attr("selected", true); // 選中 text 為 jQuery 的項
$("#select_id").val(); // 選中項的 value
$("#select_id").get(0).selectedIndex; // 選中項的索引
$("#select_id").find("option:selected").text(); // 選中項的文字
$("#select_id option:last").attr("index"); // 最大索引值
下面用 PHP 產生年、月、日三個 select,預設是 1 月,所以「日」初始有 31 天。
<select name="date_year" class="year"> <!-- 年 -->
<?php
for ($year = 1990; $year <= date("Y"); ++$year) {
?>
<option value="<?php echo $year;?>"><?php echo $year;?></option>
<?php
}
?>
</select>
<select name="date_month" class="month"> <!-- 月 -->
<?php
for ($month = 1; $month <= 12; ++$month) {
?>
<option value="<?php echo $month;?>"><?php echo $month;?></option>
<?php
}
?>
</select>
<select name="date_day" class="day"> <!-- 日 -->
<?php
for ($day = 1; $day <= 31; ++$day) {
?>
<option value="<?php echo $day;?>"><?php echo $day;?></option>
<?php
}
?>
</select>
接著用 jQuery 監聽年與月的變化,重算「日」的選項。注意每次都要先 empty() 清空,否則選項會不斷累加。
$(document).ready(function () {
$("select.month, select.year").change(function () {
$("select.day").empty(); // 非常重要,要先清空
for (var i = 1; i < 31; i++) {
var option = $("<option>").val(i).text(i);
$("select.day").append(option);
}
var month = $("select.month").val();
if ((month % 2 && month < 8) || (month % 2 === 0 && month > 7)) {
$("select.day").append("<option value='31'>31</option>");
}
if (month === 2) {
$("select.day option:last").remove();
$("select.day option:last").remove(); // 2 月共 28 天
var year = $("select.year").val();
if ((year % 4 === 0 && year % 100) || year % 400 === 0)
$("select.day").append("<option value='29'>29</option>"); // 閏年補上 29
}
});
});
以上就是 jQuery 操作 select 的增刪改查整理,希望對大家有幫助。