javascript - 使用jquery从复选框中获取价值
问题描述
我想获取不同复选框的值并将它们等同于价格并计算价格。下面是我的代码,当我提交表单时,它不会附加价格。
我尝试使用 switch case 将价格与每个值相等。
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var checked = [];
$(".sizes[value='items[]']:checked").each(function () {
checked.push($(this).val());
var price = 0;
switch (checked) {
case "small":
price:450;
break;
case "medium":
price:750
break;
case "large":
price:1500
break;
default:
checked;
}
$(".add").click(function (event) {
event.preventDefault();
$(".sprice").append(pname);
});
});
});
});
我想找到所有复选框的总数。
解决方案
复选框应该有值,不要在 jQuery 中设置价格。通过在变量中存储对值的引用,让 jQuery 处理 HTML 中的任何内容。细节在demo中注释。
/* This is optional, I don't want to write each label manually */
$(':checkbox').each(function() {
$(this).after(`<label> $${$(this).val()}</label><br>`);
});
/*
A - Prevent the form from sending data and resetting form
B - Gather all <input type='checkbox'> that are checked into a jQuery Collection
C - Map each checked checkbox value and return value as a real number.
D - Convert that map of numbers into an array and iterate through the array adding each
number and return the total sum.
E - Format the value of total as currency and display it in the output tag.
*/
var total;
function totalPrice(event) {
event.preventDefault(); //A
var checked = $(':checkbox:checked'); //B
var prices = checked.map(function() { //C
return Number($(this).val());
});
var total = prices.toArray().reduce((subTotal, price) => subTotal + price); //D
$('.total').text('$' + total.toFixed(2)); //E
};
// When form is submitted call totalPrice()
$('#shop').on('submit', totalPrice);
<form id='shop'>
<input type='checkbox' value='10.59'>
<input type='checkbox' value='2.00'>
<input type='checkbox' value='.99'>
<input type='checkbox' value='65.49'>
<input type='checkbox' value='81.99'>
<input type='checkbox' value='6.99'>
<input type='checkbox' value='5.00'>
<input type='checkbox' value='199.99'>
<input type='checkbox' value='20.00'>
<input type='checkbox' value='47.69'>
<input type='submit'><br>
<output class='total'></output>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
推荐阅读
- java - 从 RestApi 、 Retrofit 和 Rxjava 一个接一个地获取大的 json?
- python - 来自 dat 文件的数组数组
- javascript - 如果字符串不适合屏幕或在 Javascript 中确定范围,则截断字符串
- logging - 如何使用自定义日志处理程序为 Wildfly jboss 设置所有时间的最大备份日志
- wpf - ListItems 仅在调整窗口大小后显示
- c# - 未找到 nswag 命令行生成代理文件
- r - 绘图覆盖,所以在 R 循环结束时,都从列表的最后一个元素中拉出。我究竟做错了什么?
- linux - 如何在 linux 中添加 init.h 库?
- oracle11g - 当我们从富文本编辑器输入文本时,如何在 BI Publisher 报表中打印“<20%”
- python - 无法使用 delete() 从数据库中删除对象