1 回答
TA贡献1818条经验 获得超8个赞
看看它是否对你有帮助。
let checkedArr = []; // initialize the variable(type = array) to global scope.
function b(e) { // called every time a the checkbox is clicked
let totalChecked = 0; // initialize the variable with 0;
$("input[type=checkbox]." + e).each(function() { // check every checkbox with class e(e has className)
//console.log($(this));
if ($(this).is(":checked")) { // check if checkboxed is checked
totalChecked++; // increment every time
}
});
// find if class already exists -- returns the index of matched element and -1 for no match
let existIndex = checkedArr.findIndex((item) => item.class == e);
console.clear();
// console.log(existIndex);
if (existIndex != -1) { // if class exists in array, update its value
checkedArr[existIndex].checked = totalChecked;
} else { // if not insert the value as an object
checkedArr.push( {class: e, checked: totalChecked} );
}
$('.some_class').val(JSON.stringify(checkedArr)); // convert it to string and assign it to the input field
alert($('.some_class').val());
console.log(checkedArr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka1" />kaka1
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka2" />kaka2
<input onchange="b(this.className)" class="kaka" type="checkbox" name="worker_name[]" value="kaka3" />kaka3
  
<input onchange="b(this.className)" class="lala" type="checkbox" name="worker_name[]" value="lala1" />lala1
<input onchange="b(this.className)" class="lala" type="checkbox" name="worker_name[]" value="lala2" />lala2
  
<input onchange="b(this.className)" class="jaja" type="checkbox" name="worker_name[]" value="jaja1" />jaja1
<input onchange="b(this.className)" class="jaja" type="checkbox" name="worker_name[]" value="jaja2" />jaja2
<!-- Make this ↓↓ hidden -- here only for demo -->
<input type="text" name="hidden_field" class="some_class" value="" />
现在您可以看到,输入字段的值为checkeArr。然后,在您的中,controller您可以获得的价值为 -
$hidden = $this->input->post('hidden_field'); // name of your hidden field
$hidden = json_decode($hidden); // convert it back to its original form
print_r($hidden);
输出:
Array
(
[0] => stdClass Object
(
[class] => kaka
[checked] => 1
)
[1] => stdClass Object
(
[class] => lala
[checked] => 1
)
[2] => stdClass Object
(
[class] => jaja
[checked] => 2
)
)
您现在可以foreach根据需要使用它来获取其价值。
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报