« 走过2008,寄语2009 PHP下载CSS文件中的图片 »

jQuery对下拉框、单选框、多选框的处理

从本blog的日志可以看出,2007年初开始关注jQuery,已经有两年的时间了,在这两年时间里,更多的还是将jQuery当做一个很好用的工具直接运用到实际的项目和产品中。

在这期间遇到过很多jQuery的问题,没有及时的记录下来,再次遇到的时候,依旧还是得重新来过。所以决定记录下来,方便我自己查阅,也方便他人。

下拉框

//得到下拉菜单的选中项的文本(注意中间有空格)
var cc1 = $(".formc select[@name='country'] option[@selected]").text();

//得到下拉菜单的选中项的值
var cc2 = $('.formc select[@name="country"]').val();

//得到下拉菜单的选中项的ID属性值
var cc3 = $('.formc select[@name="country"]').attr("id");

//清空下拉框//
$("#select").empty();$("#select").html('');

//添加下拉框的option
$("<option value='1'>1111</option>").appendTo("#select")

稍微解释一下:

select[@name='country'] option[@selected]

表示具有name 属性,并且该属性值为’country’ 的select元素里面的具有selected 属性的option 元素。可以看出有@开头的就表示后面跟的是属性。

单选框

//得到单选框的选中项的值(注意中间没有空格)
$("input[@type=radio][@checked]").val();

//设置单选框value=2的为选中状态.(注意中间没有空格)
$("input[@type=radio][@value=2]").attr("checked",'checked');

复选框

//得到复选框的选中的第一项的值
$("input[@type=checkbox][@checked]").val();

//由于复选框一般选中的是多个,所以可以循环输出
$("input[@type=checkbox][@checked]").each(function(){
alert($(this).val());
});

//不打勾
$("#chk1").attr("checked",'');

//打勾
$("#chk2").attr("checked",true);

//判断是否已经打勾
if($("#chk1").attr('checked')==undefined){}

已经很久没有发过技术性的文章了,其实是积攒了很多在wordpress的后台,只是没有时间整理发布出来,逐渐整理发布出来吧。

“jQuery对下拉框、单选框、多选框的处理”

3条回复
  1. 注意:[@attr] 中的@在1.3里不能用了

    @esayr, 感谢提醒,刚查阅了下,果然在jQuery1.3的版本中,[@attr]不再需要写@了。

  2. 用过,不过在firefox不行!

回复留言

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

你可以使用XHTML标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>