vue中获取复选框是否被选中的值、如何用JavaScript判断复选框是否被选中

一、方法介绍 

        第一种方法:通过获取dom元素,getElementById、querySelector、getElementsByName、querySelectorAll(需要遍历,例如:for循环)

        第二种是用v-model在input复选框上绑定一个变量,通过双向绑定的特性来判断复选框是否被选中。(推荐使用)

二、演示:

第一种:被选中输出true,否则为false

document.getElementById()

html:

<input type="checkbox" id="myCheckbox">

js:

let checkbox = document.getElementById("myCheckbox");
console.log(checkbox.checked); // 输出 true 或 false

document.querySelector() 

html:

<input type="checkbox" class="myCheckbox">

js:

let checkbox = document.querySelector('.myCheckbox');
console.log(checkbox.checked); // 输出 true 或 false

document.getElementsByName() 可以获取多个,多个用for循环

html: 

<input type="checkbox" name="myCheckbox">
<input type="checkbox" name="myCheckbox">

js:

let checkboxes = document.getElementsByName("myCheckbox");
for (let i = 0; i < checkboxes.length; i++) {
  console.log(checkboxes[i].checked); // 输出 true 或 false
}

querySelectorAll()

html:

<input type="checkbox">
<input type="checkbox">

js: 

let checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < checkboxes.length; i++) {
  console.log(checkboxes[i].checked); // 输出 true 或 false
}

第二种:

html:

<input type="checkbox" class="apply-checkbox" v-model="checkboxIsChecked">

 js:在data中声明变量checkboxIsChecked:false 未选中

data(){
    return{
          checkboxIsChecked:false,
    }
}

在你做任何其他操作的时候判断checkboxIsChecked的值,如果为true表明选中了,再进行后续操作。比如:点击事件checkClick()中输出checkboxIsChecked的值

    checkClick(){
      console.log(this.checkboxIsChecked);
    }

选中输出true、未选中输出false。

checkboxIsChecked的值会随着复选框的选中与否实时改变。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年12月20日
下一篇 2023年12月20日

相关推荐