简体   繁体   English

如何使用jQuery永久禁用复选框

[英]how to disable checkbox forever using jquery

I have a website with three checkbox on it, when I click on any of the checkbox it will disable. 我有一个带有三个复选框的网站,当我单击任何一个复选框时,它将禁用。

So if I click on the first checkbox it will disable or if I click on the first and second checkbox, if I click the second checkbox and the third checkbox it will also disable but when I refresh the page it goes back to being the default checkbox not disabled 因此,如果我单击第一个复选框,它将禁用;或者,如果我单击第一个和第二个复选框,则我将单击第二个复选框,而第三个复选框也将禁用,但是当我刷新页面时,它将恢复为默认复选框未禁用

here's my code 这是我的代码

 $( "input[type='checkbox']").click(function(event){ $(this).attr('disabled', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='checkbox' value='testing one'/> <input type='checkbox' value='testing two'/> <input type='checkbox' value='testing three'/> 

thank you 谢谢

Using javascript and jQuery only, you can store the data on localStorage 仅使用javascript和jQuery,您可以将数据存储在localStorage

Here is an example: 这是一个例子:

//Get localStorage data 
var check = JSON.parse(localStorage.getItem('check')) || [];

//Disable all checkbox that is found on localStorage 
check.forEach(function(v) {
  $("input[value='" + v + "']").attr('disabled', true).prop('checked',true);
})

//Add event listener
$("input[type='checkbox']").click(function(event) {
  check.push($(this).val());                            //Push the value to the array
  localStorage.setItem('check', JSON.stringify(check)); //Save the array to localStorage 
  $(this).attr('disabled', true);                       //Disable the clicked checkbox
});

Here is a fiddle: https://jsfiddle.net/9js97xgt/ 这是一个小提琴: https : //jsfiddle.net/9js97xgt/

您可以使用localStorage,如果您不清理浏览器缓存,数据将永远保存在您的计算机上

Save the disabled checkboxes' indicies in localStorage, and then on page load, disable those indicies. 将禁用的复选框的标记保存在localStorage中,然后在页面加载时禁用这些标记。

 const disabledIndicies = JSON.parse(localStorage.disabledIndicies || '[]'); document.querySelectorAll("input[type='checkbox']") .forEach((input, i) => { if (disabledIndicies.includes(i)) { input.disabled = true; return; } input.addEventListener('click', () => { console.log(input.value); input.disabled = true; disabledIndicies.push(i); localStorage.disabledIndicies = JSON.stringify(disabledIndicies); }); }); 
 <input type='checkbox' value='testing one'/> <input type='checkbox' value='testing two'/> <input type='checkbox' value='testing three'/> <input type='checkbox' value='testing 4'/> <input type='checkbox' value='testing 5'/> <input type='checkbox' value='testing 6'/> 

Due to SO sandboxing, it won't work in the snippet, but you can see a working example here: 由于使用SO沙箱,因此无法在代码段中运行,但您可以在此处看到一个有效的示例:

https://jsfiddle.net/zd9yhas5/ https://jsfiddle.net/zd9yhas5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM