简体   繁体   中英

how can i get value of multiple checked box and perform increment using value from checked box

i can's seem to get the element by using id with query selector. Is there a way to check if the checkbox were checked using document.getelementbyId?

<script>
function checked(a,b,c){
    var marked = (a+b+c)
    document.write(marked);
}

function filled(){
    var value1 = document.querySelector("#1:checked").value;
    var value2 = document.querySelector("#2:checked").value;
    var value3 = document.querySelector("#3:checked").value;

    checked(value1,value2,value3);

    

}
<body>

<input class="chk1" id="1" type="checkbox" value="10"/>
<input class="chk2" id="2" type="checkbox" value="20"/>
<input class="chk3" id="3" type="checkbox" value="30"/>

<button name="submit" onclick="filled()" type="button" style="width: 100px; height: 100px;" >Submit</button>


</body>

Your IDs aren't valid. Even if they were (such as if you changed them to start with a letter), if a checkbox isn't checked, the querySelector will return null (so accessing the .value won't work).

Remove the IDs and use querySelectorAll instead. To make things concise, I'd give them all a single class and then the :checked pseudo-selector combined with the class will select all checked boxes.

You should also really avoid inline handlers if at all possible, they have they have way too many problems to be worth using nowadays.

 document.querySelector('button').addEventListener('click', () => { const checkedBoxes = document.querySelectorAll('.chk:checked'); const sum = [...checkedBoxes].reduce((a, b) => a + Number(b.value), 0); console.log(sum); });
 button { width: 100px; height: 100px; }
 <input class="chk" type="checkbox" value="10"> <input class="chk" type="checkbox" value="20"> <input class="chk" type="checkbox" value="30"> <button>Submit</button>

using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (eg, CSS, JavaScript, regex).

For example, the following ID is valid in HTML5:

<div id="1"> ... </div>

However, it is invalid in CSS because selectors cannot be a digit or start with a digit but can be inbetween or end with a digit.

So just change the values of your ID attributes in your html and where u referenced them in your javascript. Be sure to not miss any semi colons

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM