1. 程式人生 > >jquery中對錶單屬性的操作總結

jquery中對錶單屬性的操作總結

1.獲取下拉框的選取值/文字有以下幾種方法

(1)$("#select_id option:selected").text();//獲取文字

(2)$("#select_id").find('option:selected').text();//獲取文字

(3)$("#testSelect").val();//獲取值

(4)$("select[@name=items] option[@selected]").text();//獲取select被選中項的文字

(5)$('#select_id')[0].selectedIndex = 1;//radio單選組的第二個元素為當前選中值

//獲取索引值

(6)var checkIndex=$("#select_id").get(0).selectedIndex;//獲取Select選擇的索引值

(7)var maxIndex=$("#select_id option:last").attr("index");//獲取Select最大的索引值

2.為下拉框新增值,刪除值

(1)$("#select_id").append("<option value='Value'>Text</option>");//為Select追加一個Option(下拉項)

(2)$("#select_id").prepend("<option value='0'>請選擇</option>");//為Select插入一個Option(第一個位置)

(3)$("#select_id option:last").remove();//刪除Select中索引值最大Option(最後一個)

(4)$("#select_id option[index='0']").remove();//刪除Select中索引值為0的Option(第一個)

(5)$("#select_id option[value='3']").remove();//刪除Select中Value='3'的Option

(6)$("#select_id option[text='4']").remove();//刪除Select中Text='4'的Option

(7)$("#select_id ").get(0).selectedIndex=1;//設定Select索引值為1的項選中

(8)$("#select_id ").val(4);//設定Select的Value值為4的項選中

(9)$("#select_id option[text='jQuery']").attr("selected",true);//設定Select的Text值為jQuery的項選中

(10)為select新增新option

3.獲取文字框的值

(1)$("#text").attr("value");

(2)$("#text").val();
4.設定文字框的值
(1)$("#text").attr("value",' ');//清空內容
(2)$("#text").attr("value",'11');或者$("#text").val('11');//設定value值
5.獲取複選框的值
(1)$("input[@type=checkbox][@checked]").val();//得到複選框的選中的第一項的值
(2)$("#checkbox_id").attr("value");//得到複選框的選中的第一項的值
(3)$("input[@type=checkbox][@checked]").each(function(){//由於複選框一般選中的是多個,所以可以迴圈輸出alert($(this).val());});

6.判斷/設定複選框是否選中
(1)$("#chk1").attr("checked",'');//不打勾
(2)$("#chk2").attr("checked",true);//打勾
(3)if($("#chk1").attr('checked')==undefined)//判斷是否已經打勾
7.獲取單選框的值
(1)$("input[@type=radio][@checked]").val();//得到單選框的選中項的值(注意中間沒有空格)
8.設定單選框是否被選中
$("input[@type=radio][@value=2]").attr("checked",'checked');//設定單選框value=2的為選中狀態.(注意中間沒有空格)

注:1.select[@name='selectName'] option[@selected] 表示具有name 屬性,並且該屬性值為'selectName' 的select元素 裡面的具有selected 屬性的option 元素;可以看出有@開頭的就表示後面跟的是屬性。若有不足,請諒解和指正(~_~)另外,在jQuery升級版本中,jQuery在1.3.1版本中徹底放棄了1.1.0版本遺留下來的@符號,假如你使用1.3.1以上的版本,那麼你就不需要在屬性前新增@符號。