gpt4 book ai didi

javascript - 使用jquery将输入值格式化为货币后获取输入值

转载 作者:行者123 更新时间:2023-12-03 07:42:55 24 4
gpt4 key购买 nike

我有一个表格。在此表单上,当我添加行项目时,我保存输入值,然后将其添加到表单中。这部分有效。请记住,表单没有被提交,我只是动态添加到 dom

在我保存的表格部分有一个价格输入。我正在使用 jquerypriceformat 插件将价格格式化为价格格式。例如,111 变为 1.11 美元。如果我不使用该插件,它就可以工作。该插件确实按预期工作。我认为我的问题是,在我输入后,值正在更改,我需要以某种方式保留该值。

这是一个 fiddle https://jsfiddle.net/ks2z5mdo/7/

我认为 fiddle 能更好地显示问题所在。基本上,当您输入描述、数量和价格时,价格会被格式化,然后点击添加按钮,除了价格之外的所有数据都会被保存。

我该如何解决这个问题?

首先是表单

<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);

这会将值保留为数字,而不是最初的字符串。这是fiddle有效。

关于javascript - 使用jquery将输入值格式化为货币后获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35331104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com