繁体   English   中英

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

[英]How do I get my checkbox values and option values to add up and enter the sum into my text area?

我正在尝试制作一个结帐/购物页面,您可以在其中选择要购买的商品,选择运输价格,然后在单击“计算运输”时单击“选择的价格”。

我有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将其设置为textarea。

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

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

如果您使用的是按钮类型Submit,那么它将阻止您将表单提交到script.php,除非您阻止它使用javascript提交。

我建议您将#button类型设为按钮而不是提交。

计算您可以使用javascript这样的东西

var inputs, index, sum;
sum = 0;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
    var el = inputs[index];
    if (el.type && el.type === 'checkbox' && el.checked) {
        sum += inputs[index].value;
    }
}

另外,您应该为复选框使用适当的名称,因为在实际提交表单时,它们将在scripts.php中引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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