首页 > 解决方案 > 使用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);
            });
        });
    });
});

我想找到所有复选框的总数。

标签: javascriptjquery

解决方案


复选框应该有值,不要在 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>


推荐阅读