簡體   English   中英

使用輸入框值乘以復選框值 - Jquery

[英]Multiply Checkbox Value with Input Box Value - Jquery

我目前正在努力從復選框中獲取值,並使用jQuery與輸入框中的值相乘。

當勾選復選框以詢問數量時,我會顯示一個div,此后我必須將數量乘以復選框的值。

這是當前的代碼:

$(document).ready(function () {
    var sum = 0;
    var qty = 0;

    $("input[type=checkbox]").change(function () {
        recalculateQty();
        recalculateCheck();
        if ($('#1').is(':checked')) {
            $('#checked-1').show();
        } else {
            $('#checked-1').hide();
        }
        if ($('#2').is(':checked')) {
            $('#checked-2').show();
        } else {
            $('#checked-2').hide();
        }
        if ($('#3').is(':checked')) {
            $('#checked-3').show();
        } else {
            $('#checked-3').hide();
        }
    });

    function recalculateQty() {
        $('.qty').keyup(function () {
            $('.qty').each(function () {
                qty += parseInt(this.value, 10);
                recalculateCheck();
            });
        });
    }

    function recalculateCheck() {
        var sum = 0;
        $("input[type=checkbox]:checked").each(function () {
            sum += parseInt($(this).val());
        });
        $('.qty').keyup(function () {
            $('.qty').each(function () {
                qty += parseInt(this.value, 10);
            });
        });
        $('#total').val(sum * qty);
    }
});

<input type="checkbox" id="1" value="30" name="1" />
<input type="checkbox" id="2" value="60" name="2" />
<input type="checkbox" id="3" value="90" name="3" />

<div style="display:none;" id="checked-1">
    <input type="text" name="product_1_qty" id="product_1_qty" placeholder="Quantity" class=" qty" value="0" />
</div>

http://jsfiddle.net/isherwood/9vRtJ/1/

您正在嘗試使用total ID設置元素值作為最終結果,但您的html代碼中沒有此類元素。
只需在你的html代碼中添加這個元素(這里我放了另一個文本框):

<input type="text" id='total'>

查看您的修復實時演示

或者你可以使用更好的編碼:(閱讀評論) - 工作演示

$(document).ready(function () {
    var sum = 0;
    var qty = 0;
    $("input[type=checkbox]").change(function () {
        if ($('#1').is(':checked')) {
            $('#checked-1').show(); 
        } else {
            $('#checked-1').hide();
        }
    });
     $('.qty').keyup(function () { // if user typed anyting in the Quantity
          sum = parseInt($('#1').val()); // get checkbox value and change the data type to int
          qty = parseInt($(this).val()); // get Quantity value and change the data type to int
          //console.log(sum,qty);
          if(sum && qty) { // if the values was not empty
              $('#total').val(sum * qty); // show the result in the total element
          } else { // if the values was empty
              $('#total').val(''); // clear the result textbox
          }
     });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM