- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Sum of Radio button values jQuery?
Let’s say we have marks records and we need to sum them. The records are displayed in Radio Button −
Marks1
<label><input type="radio" name="firstMarks" value="75" /> 75</label> <label><<input type="radio" name="firstMarks" value="57" /> 57 </label>
Marks 2
<label><input type="radio" name="secondMarks" value="89" /> 89</label> <label><input type="radio" name="secondMarks" value="54" /> 54</label>
Example
Following is the complete code to loop and find the sum −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <form> <p>Marks1</p> <p> <label><input type="radio" name="firstMarks" value="75" /> 75</label> <label><input type="radio" name="firstMarks" value="57" /> 57</label> </p> <p>Marks2</p> <p> <label><input type="radio" name="secondMarks" value="89" /> 89</label> <label><input type="radio" name="secondMarks" value="54" /> 54</label> </p> <input type="button" value="calculate" onclick="getResult()" /> </form> </body> <script> function getResult() { var firstMark = document.getElementsByName('firstMarks'); var secondMark = document.getElementsByName('secondMarks'); var total = 0; firstMark.forEach((evnt) => { if (evnt.checked) { total = total + parseInt(evnt.value); return; } }); secondMark.forEach((evnt) => { if (evnt.checked) { total = total + parseInt(evnt.value); return; } }); console.log("Total Marks=" + total); } </script> </html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
Output
This will produce the following output −
Now, select the value from the radio button −
Click the button “calculate”. You will get the following output on console −
Advertisements