How to get all checked checkboxes

前端 未结 4 648
离开以前
离开以前 2020-11-27 03:30

I have a set of input checkboxes with the same name and I would like to determine which checkboxes have been checked using javascript, how can I achieve that? I know only ho

4条回答
  •  -上瘾入骨i
    2020-11-27 04:02

    For a simple two- (or one) liner this code can be:

    checkboxes = document.getElementsByName("NameOfCheckboxes");
    selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
    

    Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

提交回复
热议问题