用Javascript和/或jQuery计算select选项的值
Calculate the values from select option with Javascript and/or jQuery
首先:我知道我应该提供我的解决方案并解释什么不起作用。但不幸的是,我还在学习HTML和PHP,所以我没有Javascript的经验。我想,我希望有人能帮助我。
在我的网站上有一个表单。在这个表单中有这样的代码:
<select name="size">
<option value="" disabled selected>Size ↓</option>
<option value="AAA">AAA (10 €)</option>
<option value="BBB">BBB (20 €)</option>
<option value="CCC">CCC (30 €)</option>
<option value="DDD">DDD (40 €)</option>
</select>
<select name="discount">
<option value="" disabled selected>Option ↓</option>
<option value="Option1">Option 1 (0 %)</option>
<option value="Option2">Option 2 (-5 %)</option>
<option value="Option3">Option 3 (-8 %)</option>
</select>
<select name="method_of_payment">
<option value="" disabled selected>Method of payment ↓</option>
<option value="transfer">Transfer (0 % cashback)</option>
<option value="debit">Debit (-3 % cashback)</option>
</select>
这就像一个商店。我想用Javascript预先计算用户的最终价格。(我不想重新加载网站。否则我会用PHP来做。)我想要这样的输出:The final price is 18,43 €. You saved 1,57 €
.
从"method_of_payment"返回的现金必须在尺寸和折扣的最终价格上。这意味着对于size = BBB
、discount = Option2
和method_of_payment = debit
: 20-(20/100*5)=19 | 19-(19/100*3)=18,43 €
另一个问题是,当表单提交时,我在数据库中有AAA
和Option1
和transfer
等值。据我所知,Javascript需要在value=""
字段中计算值。还是有变通的办法?
确保在每个选项的value属性中存储实际值:
<select name="size">
<option value="" disabled selected>Size ↓</option>
<option value="10">AAA (10 €)</option>
<option value="20">BBB (20 €)</option>
<option value="30">CCC (30 €)</option>
<option value="40">DDD (40 €)</option>
</select>
使用jQuery
,你可以做如下的事情:
var price = $('select[name=size]').val() * ($('select[name=discount]').val() * 1/100) * $('select[name=method_of_payment]').val();
如果你有一个HTML元素,比如标签,你可以这样显示它:
$('.mylabel').text(price);
我猜你以前没有做过这件事。因此,更进一步,您需要认为每次选择值发生变化时都需要重新运行计算。一个完整的例子应该是这样的:
$(document).ready(function () {
// this will run on every select value change. if you want it to only run for those specific selects, add the same class in all of them and change the selector to $('select.yourclass')
$('select').on('change', function() {
$('.mylabel').text($('select[name=size]').val() * ($('select[name=discount]').val() * 1/100) * $('select[name=method_of_payment]').val());
});
});
** EDIT **
工作示例:
https://jsfiddle.net/2cs8vcLo/相关文章:
- 根据select选项元素将表单重定向到不同的URL
- jQuery动态表单显示在select选项上
- 如何在触发事件后选择select选项
- jQuery:根据select选项中的每页项目进行分页
- 使用JavaScript删除多个select选项
- 使用select选项转换时间.使用javascript
- 使用angularjs解析JSON,并选择select选项
- 使用jQuery在select选项上设置HTML数据属性
- 如何防止onclick事件在select选项中触发
- 如何在angular js中的select选项中获取所选项目id
- ng-select 选项在与自定义指令一起使用时加倍
- jQuery未能将JSON数据附加为select选项
- 如何将html中select选项的输入与javascript一起使用
- 使用VueJs获取Select选项文本
- 从jquery中的select选项添加两个不同的数组值(text&value)
- select选项在angularjs中不显示
- jQuery v 1.1x更改select选项的值
- 将select选项添加到id中
- 基于select选项的javascript动态表单生成
- Select选项包含在验证模型MVC时不起作用