下拉選單(DropDownList / select)是表單中不可或缺的元素。jQuery 提供了豐富的方法來操作它的取值、賦值、增刪與遍歷。以下整理最常見的 16 種操作寫法,方便日後查閱。
//獲取選中項的 Value 值:
$('select#sel option:selected').val();
//或者
$('select#sel').find('option:selected').val();
//獲取選中項的 Text 值:
$('select#sel option:selected').text();
//或者
$('select#sel').find('option:selected').text();
$('select#sel').get(0).selectedIndex;
$('select#sel option:last').attr("index")
$('select#sel')[0].options.length;
//或者
$('select#sel').get(0).options.length;
$('select#sel option:first').attr('selected','true')
//或者
$('select#sel')[0].selectedIndex = 0;
$('select#sel option:last).attr('selected','true')
$('select#sel')[0].selectedIndex =索引值;//索引值=0,1,2....
$('select#sel').attr('value','4');
//或者
$("select#sel option[value='4']").attr('selected', 'true');
$("select#sel option[value='3']").remove();
$(" select#sel option ").eq(索引值).remove();//索引值=0,1,2....
//如刪除第 3 個:
$(" select#sel option ").eq(2).remove();
$(" select#sel option ").eq(0).remove();
//或者
$("select#sel option:first").remove();
$("select#sel option:last").remove();
$("select#sel").remove();
$("select#sel").append("<option>f</option>");
$("select#sel").prepend("<option>0</option>");
$(' select#sel option ').each(function (index, domEle) {
//寫入代碼
});
把這份清單收藏起來,日常處理下拉選單時幾乎所有情境都能對應到其中一種寫法。核心觀念是:取值多用 :selected 選擇器搭配 val()/text(),增刪則善用 append、prepend、remove 與 eq(),遍歷時用 each() 即可。