- get
- 取出選擇的值
1
2
$(
"select#Club"
).val();
$(
\'select#Club option:selected\'
).text();
以上2方法在單選時相同,但複選時,
val()會用逗號分開 ex. AA, BB
text()不會 ex. AABB - 取出array
1
2
3
$(
"select#Club"
).children(
"[@selected]"
).each(
function
(){
alert(
this
.text());
});
- 取出選擇的值
- set
- 使某option變為selected
1
2
3
4
5
6
7
8
9
$(
"#select1"
).children().each(
function
(){
if
($(
this
).text()==
"option you want"
){
//jQuery給法
$(
this
).attr(
"selected"
,
"true"
);
//或是給selected也可
//javascript給法
this
.selected =
true
;
}
});
- 讓新增的option直接為selected
1
2
3
4
var
option = jQuery(
"new option"
);
$(
\'select#Club\'
).append(option);
$(option).attr(
"selected"
,
"true"
);
//讓option為selected
$(
\'select#Club\'
).trigger(
"change"
);
//最後要觸發select的change事件
- select下拉框的第二個元素為當前選中值
$(\'select#Club)[0].selectedIndex = 1;//不知為何要加[0]
=========== K. T. Chen 提到 ==========================
在$("")加[0]的意思是把jQuery物件轉為DOM物件。這樣子jQuery物件才能使用DOM底下的selectedIndex方法。
- 使某option變為selected
- event
//改變時的事件
1
2
3
4
5
6
7
8
9
$(
"select#Club"
).change(
function
(){
//事件發生
//一次印出
alert($(
this
).val());
//印出選到多個值
jQuery(
\'option:selected\'
,
this
).each(
function
(){
alert(
this
.value);
});
});
- 移除 removeOption(index/value/regex[, selectedOnly])
1
$(
\'select#Clubs option:selected\'
).remove();
//純javascirpt
1 2 3 4 | <select onchange= "alert(\'Index: \' + this.selectedIndex + \'\\nValue: \' + this.options[this.selectedIndex].value)" > ... </select> |