向包含货币代码的价格字段添加百分比

Adding percentage to a price field incl. currency code

本文关键字:字段 添加 百分比 包含 货币 代码      更新时间:2023-09-26

我正试图通过javascript向价格字段添加10%,但到目前为止我还没能添加,希望你们能提供帮助。

包括货币代码等的字段

我确实在这个方向上尝试了一些东西:

<script type="text/javascript">
    $( document ).ready(function() {
      var Total = $("#cashamount");
      Total.val(Total.val() * 1.1);
    });
</script>

但这并没有奏效;(

价格字段显示如下。

<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>

在价格上加上10%后,在这个例子中应该说:

<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>

任何想法都是受欢迎的,我真的很感激在这件事上的帮助,因为我确实认为这很简单,但我不太喜欢Javascript。

首先:(下面的解决方案)

.val()方法主要用于获取表单元素的值例如输入、选择和文本区域。在元素的情况下.val()方法返回一个数组,该数组包含每个选定的选项;如果没有选项,则返回null,jQuery文档

.text()方法不能用于表单输入或脚本。设置或获取input或textarea元素的文本值,使用.val()方法要获取脚本元素的值,请使用.html()方法,jQuery文档

因此,下一个解决方案是:

var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9'.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this

这是JsFiddle

var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%    
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;

所以你可以为此创建一个函数:

function updateVal(elem){
    var x = elem.html(); // Fethching the value
    var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
    var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
    var newAmmt = intAmmt*1.1; // Incrementing by 10%    
    var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
    elem.html(y); // Setting the html;
}

并将其用作:

$(document).ready(function(){
   updateVal($("#cashamount"))
});