jQuery操作checkbox、radio、select选择

简单的记录jQuery操作checkbox、radio、select选中,是否选中

是否选中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let isChk = $(el).is(':checked') // 是否选中 true or false
if(isChk){
do something...
}
let isChk2 = $(el).attr('checked') // 是否选中 true or false
if(isChk2){
do something...
}
or
if(isChk2 == true){
do something...
//isChk2 是布尔型 不是字符串
}

设置全选 全不选 反选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//jQuery 1.6+
$(el).prop("checked", true);
$(el).prop("checked", false);
$('input[type=checkbox]').attr('checked',true) //全选中
$('input[type=checkbox]').removeAttr('checked') //全不选
$('input[type=checkbox]').attr('checked',false) //全不选
//反选
$('input[type=checkbox]:checked').each(function(){
let self = $(this)
$(this).attr('checked', !self.attr('checked'))
})
//获取遍历选中的val值(第1种)
$('input[type=checkbox]:checked').each(function(){
let self = $(this)
console.log(self.val())
})
//获取遍历选中的val值(第2种)
$('input[type=checkbox]').each(function(){
let self = $(this)
let isChk = self.is(':checked')
if(isChk){
console.log(self.val())
}
})

获取选择的个数

1
2
let isLen = $('input[type=checkbox]:checked').length
alert(isLen)

select选择

1
2
3
4
5
6
7
8
比如<select class="selector"></select>
$(".selector").val("pxx") //设置value为pxx的项选中
$(".selector").find("option[text='pxx']").attr("selected",true) //设置text为pxx的项选中
$(".selector").val() //获取当前选中项的value
$(".selector").find("option:selected").text() //获取当前选中项的text
$(".selector option:selected") //获取选中的项
vincentSea wechat
一颗稻草的价值,到底是多少呢?想知道的话,就订阅吧!