简体   繁体   中英

document.querySelector null in js

i have this code>>

 function myFunction() { var a = document.querySelector('input[name="qa1"]:checked').value; var b = document.querySelector('input[name="qa2"]:checked').value; var sum = a + b; alert(sum) } 
 <label><input name="q1" value="5" required="" type="radio"> answare</label> <label><input name="q2" value="10" required="" type="radio"> answare2</label> <input class="submit-button" value="Score my Answers" name="submit" type="submit" onclick="myFunction()"> 

i want get alert with sum of q1 and q2 when click Score my Answers button and thay are checked please help

There is typo in name. Secondly the value is a string so the output will be 510 because of string concatenation. Use parseInt to convert string to num before doing addition

 function myFunction() { var a = document.querySelector('input[name="q1"]:checked').value; var b = document.querySelector('input[name="q2"]:checked').value; var sum = parseInt(a, 10) + parseInt(b, 10); alert(sum) } 
 <label><input name="q1" value="5" required="" type="radio"> answare</label> <label><input name="q2" value="10" required="" type="radio"> answare2</label> <input class="submit-button" value="Score my Answers" name="submit" type="submit" onclick="myFunction()"> 

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