我在我的php项目中使用了twig。
我有一个包含许多复选框的表单。我需要在javascript中恢复数组中复选框的所有选中值。
这是javascript:
<script type="text/javascript" charset="utf-8" async defer>
document.getElementById("{{ value }}").onclick = function() { /* {{ value }} is value of my checkboxe, twig variable it matches like a php variable */
if ( this.checked ) { /* check if checkboxes are checked */
var valueChecked = this.value;
console.log(valueChecked); /* just to display the value for debug */
var valueArray = []; /* I create an array */
/* here I need to put all my checkboxes values in allCheckedConfig */
} else {
console.log("removed " + this.value ); /* just to debug, check if checkboxes are unchecked */
}
};
</script>
如何填充我的valueArray[]
?
您可以使用
map
函数获取如下所示的数组。
var elems = document.querySelectorAll('input[type=checkbox]:checked');
var valueArray = Array.prototype.map.call(elems, function (obj) {
return obj.value;
});
console.log(valueArray)
.push
是你需要
var valueArray = [];
document.getElementById("{{ value }}").onclick = function() {
if ( this.checked ) {
var valueChecked = this.value;
console.log(valueChecked);
valueArray.push(valueChecked);
console.log(valueChecked); // Should give you the array.
} else {
console.log("removed " + this.value );
}
};
如果你的网站上有jQuery,你可以观看serializeArray函数
试试这个
var arr=$('input[type=checkbox]:checked').map(function(k,v){return $(v).val();});