簡體   English   中英

在使用jQuery將其格式化為貨幣后獲取輸入值

[英]getting input value after it has been formatted to currency with jquery

我有一個表格。 在此表單上,當我添加訂單項時,我保存了輸入值,然后將其添加到表單前。 這部分有效。 請記住,表單尚未提交,我只是動態添加到dom

在我保存的表格的一部分中,有一個價格輸入。 我正在使用jquerypriceformat插件將價格格式化為價格格式。 例如111變成$ 1.11。 如果我不使用該插件,它將起作用。 該插件確實可以正常工作。 我認為我的問題是,在鍵入內容后,值將被更改,因此我需要以某種方式保留該值。

這是一個小提琴https://jsfiddle.net/ks2z5mdo/7/

我認為小提琴會更好地說明問題所在。 基本上,當您輸入描述時,輸入數量和價格,價格會被格式化,然后點擊添加按鈕,所有價格除外的數據都會被保存。

我該如何解決?

首先是表格

<div class="form-row">
    <strong>Line Items:</strong>
    <br>
    <div class="line-items">
        <div class="line-item">
            <div class="line-item-box description">
                <label>Description:</label>
                <textarea name="description" id="description"></textarea>
            </div><!--
         --><div class="line-item-box quantity">
                <label>Quantity:</label>
                <input type="text" name="quantity" id="quantity">
            </div><!--
         --><div class="line-item-box price">
                <label>Price:</label>
                <input type="text" name="price" id="price">
            </div>
            <button class="btn add-item">Add Item</button>
        </div>
    </div>  
</div>

然后是jQuery

$(document).ready(function() {
    $('#price').priceFormat();
    $('.add-item').click(function() {
        if ($('description, #quantity, #price').filter(function() { return $(this).val(); }).length > 0) {
            var description = $('#description').val();
            var quantity = $('#quantity').val();
            var price = $('#price').val();
            $('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price">' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
             return false;
         } else {
             alert('Line item empty');
         }
    });
    $(document).on('click', '.remove-btn', function() {
        $('.line-item').remove();
    });
});

您的var price = $('#price').val(); 在您要獲取的實際值前面添加一個$和一個空格。 因此,一種解決方案是獲取該值的子字符串以刪除$:

var price = $('#price').val().substring(2);

這會將值保留為數字,而不是原來的字符串。 這是一個有效的小提琴

暫無
暫無

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

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