javascript - 如何让我的复选框值和选项值相加并将总和输入到我的文本区域?

标签 javascript html css sum

我正在尝试创建一个结帐/购物页面,您可以在其中选择要购买的商品,选择运费,当您单击计算运费时,所选商品的全价将显示在文本区域中。

我有 3 个具有三个不同值的复选框和 3 个具有三个不同值的选项。我希望能够将选定的复选框和选项相加,并且我希望总和(答案)显示在页面底部的文本区域中。按下按钮后,答案将在文本区域中弹出。我的按钮 ID 是#button。

如何使用 javascript 完成此操作?

如果有人知道如何做到这一点,将不胜感激,我正在学习如何使用 javascript,我会发现阅读您的解决方案是一种非常有用的学习方式。

这是我的 html 中的一个片段:

<body>
<form action="script.php" method="get" id="myform">
<h1>Select a product below:</h1>

<div>

<p>Product 1</p> &#8364;25.00<input type = "checkbox" name = "25" value = "25" id="cb1" class="sum"><br>
<p>Product 2</p> &#8364;50.00<input type = "checkbox" name = "50" value = "50" id="cb2" class="sum">   <br>
<p>Product 3</p> &#8364;100.00<input type = "checkbox" name = "100" value = "100" id="cb3"                 class="sum">

</div>

<h2>
Where do you want the products delievered to:   
</h2>

<div><select>
<option value="select">Select a shipping option..</option>
<option value="2">Ireland (2.00)</option>
<option value="3">Rest of Europe (3.00)</option>
<option value="7">Rest of World (7.00)</option>
</select></div>

<div>
<textarea cols="20" rows="1" id="shipping">Shipping</textarea>
</div>

<input type = "submit" 
value = "Calculate Shipping"
id="button"
>
</form>
</body>

这是我的CSS:

h1{
font-weight: normal;
font-size: 20px;
margin-top: 50px;
margin-left: 50px;
}

p{
margin-left: 50px;
margin-right: 80px;
font-size: 20px;
font-weight: normal;
display: inline-block;}

input{
display: inline-block;
}

h2{
font-weight: normal;
font-size: 20px;
margin-left: 50px;
display: inline-block;
float: left;
}

select{
display: inline-block;
margin-top: 20px;
margin-left: 20px;
}

body {
font-size: 20px;
}

#shipping{
margin-left: -370px;
margin-top: 20px;
font-family: arial;
display: inline-block;
}

#button{
display: inline-block;
float: right;
margin-right: 1000px;
margin-top: -26px;
}

textarea {resize: none;}

抱歉我的问题太长了,如果有人能帮助我就太好了:)

最佳答案

您可以使用 Javascript 来执行此操作。使用 Jquery 获取输入的所有值,对它们求和并使用 Jquery 将它们设置为文本区域。

var numbers = $("input:checked").val();
var sum = numbers.reduce(function(sum, i) { return sum + i}, 0);

$("#shipping").val(sum);

关于javascript - 如何让我的复选框值和选项值相加并将总和输入到我的文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702514/

相关文章:

javascript - lodash 从数组中选取对象字段

javascript - PHP 包含的 Node.js 等价物是什么?

HTML5 : Make an entire table row clickable without javascript

javascript - 查找哪个对象调用了函数

javascript - 带十进制的 iPhone 数字键盘,适用于可编辑 DIV 上的 Web 应用程序

带有 jPlayer 的 Javascript 模式

javascript - jquery如何根据定义的变量获取相关id的信息

html - 嵌套的 flex 容器在 Firefox 中溢出

html - 为什么我的 Div 元素不能保持一致?

css - 有没有一种简单的方法可以在 asp.net cssclass 中添加/删除/替换类