JQuery選中select元件被選中的值
阿新 • • 發佈:2019-01-25
jquery獲取select選擇的文字與值
獲取select :
獲取select 選中的 text :
$(“#ddlregtype”).find(“option:selected”).text();
獲取select選中的 value:
$(“#ddlregtype “).val();
獲取select選中的索引:
$(“#ddlregtype “).get(0).selectedindex;
設定select:
設定select 選中的索引:
$(“#ddlregtype “).get(0).selectedindex=index;//index為索引值
設定select 選中的value:
(“#ddlregtype “).attr(“value”,”normal“);(“#ddlregtype “).val(“normal”);
$(“#ddlregtype “).get(0).value = value;
設定select 選中的text:
var count=$("#ddlregtype option").length; for(var i=0;i<count;i++) { if($("#ddlregtype ").get(0).options[i].text == text) { $("#ddlregtype ").get(0).options[i].selected = true; break; } } $("#select_id option[text='jquery']").attr("selected", true);
設定select option項:
$("#select_id").append("<option value='value'>text</option>"); //新增一項option $("#select_id").prepend("<option value='0'>請選擇</option>"); //在前面插入一項option $("#select_id option:last").remove(); //刪除索引值最大的option $("#select_id option[index='0']").remove();//刪除索引值為0的option $("#select_id option[value='3']").remove(); //刪除值為3的option $("#select_id option[text='4']").remove(); //刪除text值為4的option
清空 select:
$("#ddlregtype ").empty();
工作需要,要獲得兩個表單中的值。如圖:
如何獲得從左邊選擇框新增到右邊選擇框中的值?我想了想用網頁特效可以獲得,這裡用了比較流行的jquery。
js程式碼如下:
//獲取所有屬性值 var item = $("#select1").val();
$(function(){
$('#select1').each( //獲得select1的所有值
function(){
$('button').click(function(){
alert($('#select2').val()); //獲得select2中的select1值
});
});
})
</script>
值得注意的是,不能直接寫成
$(function(){
$('#select2').each( //獲得select1的所有值,因為前面講選項從左邊新增到右邊,jquery其實並沒有真正將值從左邊傳到右邊。
function(){
$('button').click(function(){
alert($(this).val()); //獲得select2中的select1值
});
});
})
html:
選項1
選項2
選項3
選項4
選項5
選項6
選項7
選中新增到右邊>>
全部新增到右邊>>
<<選中刪除到左邊
<<全部刪除到左邊
使用JQuery,Ajax呼叫動態填充Select的option選項
//繫結ClassLevel1單擊事件
$("#ClassLevel1").change(function () {
var id = $("#ClassLevel1").val();
var level2 = $("#ClassLevel2");
level2.empty();
$("#ClassLevel3").hide();
$.ajax({
url: "./askCommon.ashx?action=getclasslevel&pid=" + id,
data: { "type": "ajax" },
datatype: "json",
type: "get",
success: function (data) {
var json = eval_r(data);
for (var ind in json) {
level2.append($("<option value='" + json[ind].id + "'>" + json[ind].typename + "</option>"));
}
}
});
})