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以上的版本,那么你就不需要在属性前添加@符号。

猜你喜欢

转载自www.cnblogs.com/zhiyanwenlei/p/9946214.html
今日推荐