2016-02-11 33 views
0

我有一個表單。在此表單上,我添加訂單項時保存了輸入值,然後將其添加到表單中。這部分工作。請記住,表單沒有被提交我只是將dom動態添加到獲得輸入值後,它被格式化爲jQuery的貨幣

在我保存的表格部分有價格輸入。我正在使用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(); 
    }); 
}); 

回答

1

var price = $('#price').val();增加了$和您想獲得實際值前面的空間。因此,一種解決方案是讓這個值的字符串中刪除$:

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

這將使值爲數字,而不是它最初做成的字符串。這是一個fiddle工作。

+0

啊,但那麼得到保存的價值並不是美分和美元符號的全價。有沒有辦法讓貨幣保持原樣? – badsyntax

+0

我想你將不得不在美元符號上再加上美元符號,因爲我不認爲當有美元符號的時候,有一種方法可以將數字乘以數字。 –

+0

我已經更新它在最後顯示美元符號。您只需在前面的價格*數量前添加「$」即可。 –