JavaScript 对象数组插入新的对象数组和控制台日志



我正在尝试创建一个动态对象数组(如键:值(。 我想插入每个键(单击的类名(和值(检查的数量(。 我编写了控制台.log因此我可以从 PHP 中的数组中获取值。 问题是:它不会以这种方式插入新对象。

var countChecked = function() {
var checked = {};
var n = $( '.'+ this.className + ':checked' ).length;
checked.push({'this.className',n});
console.log(checked);
alert( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );

也许,这个片段会为你工作。我也参考了你之前的问题。我已经在代码片段本身中解释了代码。看看它是否对你有帮助。

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
&emsp;&emsp;
<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
&emsp;&emsp;
<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来获取其值。

相关内容

  • 没有找到相关文章

最新更新