I am usiing twig in my php project.
I have a form which contains many checkboxes. I need, in javascript to recover all checked values of the checkbox in an array.
This is the 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>
How can I populate my valueArray[]
?
You can get the array like following using map
function.
var elems = document.querySelectorAll('input[type=checkbox]:checked');
var valueArray = Array.prototype.map.call(elems, function (obj) {
return obj.value;
});
console.log(valueArray)
.push
is what you need
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();});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.