如何用jQuery计算单选按钮的数值之和
在这篇文章中,我们将看到如何使用jQuery计算单选按钮的数值之和。为了增加单选按钮的值,我们将使用加法算术运算。
方法:首先,我们将使用单选按钮来选择两个数字,即数字1和数字2。如果用户点击单选按钮的值,那么用户就会选择该值,并通过使用jQuery val()方法获得该值,并使用parseInt()方法将该值转换成数字。在选择了两个数字值后,用户点击 “计算总和 “按钮来计算所选单选按钮值的总和。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Calculate the sum of radio
button values using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
h1,
h3 {
text-align: center;
}
.GFG {
width: 350px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
Calculate the sum of radio
button values using jQuery
</h3>
<div class="GFG">
<p>
<label for="num1">Select First Number: </label>
<input type="radio" name="fnum" value="10">10
<input type="radio" name="fnum" value="20">20
<input type="radio" name="fnum" value="30">30
</p>
<p>
<label for="num1">Select Second Number: </label>
<input type="radio" name="snum" value="10">10
<input type="radio" name="snum" value="20">20
<input type="radio" name="snum" value="30">30
</p>
<button>Calculate Sum</button>
<p class="res"></p>
</div>
<script>
(document).ready(function () {
let fnum = 0, snum = 0;
('input[name="fnum"]').on("click", function () {
fnum = parseInt(('input[name="fnum"]:checked').val());
});
('input[name="snum"]').on("click", function () {
snum = parseInt(('input[name="snum"]:checked').val());
});
("button").on('click', function () {
let sum = fnum + snum;
$(".res").html("Sum of Two Numbers: " + sum);
});
});
</script>
</body>
</html>
输出: