jQuery常用方法

来源:https://www.hellojava.com/article/84

(1) 如何获取checkbox,并判断是否选中

$("input[type='checkbox']").is(':checked') 
//返回结果:选中=true,未选中=false

(2) 获取checkbox选中的值

var chk_value =[]; 
$('input[name="test"]:checked').each(function(){ 
    chk_value.push($(this).val()); 
});

(3)checkbox全选/反选/选择奇数

$("document").ready(function() {
    $("#btn1").click(function() {
        $("[name='checkbox']").attr("checked", 'true'); //全选 
    }) $("#btn2").click(function() {
        $("[name='checkbox']").removeAttr("checked"); //取消全选 
    }) $("#btn3").click(function() {
        $("[name='checkbox']:even").attr("checked", 'true'); //选中所有奇数 
    }) $("#btn4").click(function() {
        $("[name='checkbox']").each(function() { //反选 
            if ($(this).attr("checked")) {
                $(this).removeAttr("checked");
            } else {
                $(this).attr("checked", 'true');
            }
        })
    })
})

(4)获取select下拉框的值

$("#select").val()

(5)获取选中值,三种方法都可以

$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='rd']:checked").val();

(6)设置第一个radio为选中值

$('input:radio:first').attr('checked', 'checked');

或者

$('input:radio:first').attr('checked', 'true');

(7)设置最后一个Radio为选中值:

$('input:radio:last').attr('checked', 'checked');

或者

$('input:radio:last').attr('checked', 'true');

(8)根据索引值设置任意一个radio为选中值:

$('input:radio').eq(索引值).attr('checked', 'true');//索引值=0,1,2....

或者

$('input:radio').slice(1,2).attr('checked', 'true');

(9)根据Value值设置Radio为选中值

$("input:radio[value='rd2']").attr('checked','true');

或者

$("input[value='rd2']").attr('checked','true');
原文地址:https://www.cnblogs.com/pcx105/p/8456420.html