Problem description: There are multiple checkboxes, implemented using input simulation. I want to put the corresponding value into the array when clicked, and delete the corresponding value in the array when unchecked. How to achieve this?
I have done something similar before. The general idea is: loop checkbox, when the current checkbox is checked, set the current checked status and then take the input value and pass it into the array array.push($(this).val()), Unchecking is the same operation. In the end, just remove the input value.
I was bored and wrote something for a while, and copied @shangguanyuanheng's code. I don't understand why I don't need to use native jquery, and the title doesn't say it can't be used, right?
code:
<html>
<head>
<title>
title
</title>
<meta name="author" content="zsdroid">
<script id="jquery_183" type="text/javascript" class="library" src="jquery-1.8.3.min.js"></script>
</head>
<body>
<input type="checkbox" class="radioSelect" value="1">1
<input type="checkbox" class="radioSelect" value="2">2
<input type="checkbox" class="radioSelect" value="3">3
</body>
<script>
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
let arr=[];
$('.radioSelect').bind("change",(e)=>{
var target=$(e.target);
var value=target.val();
let ischecked=target.is(":checked");
if(ischecked){
//push
arr.push(value);
}else{
//remove
arr.remove(value);
}
console.info(arr);
}
);
</script>
</html>
I have done something similar before. The general idea is: loop checkbox, when the current checkbox is checked, set the current checked status and then take the input value and pass it into the array array.push($(this).val()), Unchecking is the same operation. In the end, just remove the input value.
Change your thinking, write a checkbox change event, and get all selected items (checked=true), that’s it
I was bored and wrote something for a while, and copied @shangguanyuanheng's code. I don't understand why I don't need to use native jquery, and the title doesn't say it can't be used, right?
code:
Online trial
Hope to make bricks~