javascript - 将值格式化为 "doesn' t work'

标签 javascript jquery

enter image description here

使用函数格式化值并像这样调用:

$(".vlrTotal").val(formatReal(formatarValor($(".vlrTotal").val())));

我的 HTML:

<td>
    <input readonly type="text" name="vlrTotal[]" value="<?php echo $item['VwEstPedOnlineItens']['vlr_custo_total']; ?>" class="vlrTotal" style="width: 100%;"/>
</td>

结果如上图所示。

现在如果我取消格式化该值的功能,结果是这样的: enter image description here

问题是,在格式化值后,所有输入 (".vlrTotal")显示相同的值(第一个),但是当我检查元素时,该值显示正确的值。如果我取消格式化该值的功能,它就会“起作用”。

我不知道该怎么办了。

PS:控制台.log:

input.vlrTotal property value = "7.199,28" attribute value = "2799.72"

input.vlrTotal property value = "7.199,28" attribute value = "2399.76"

最佳答案

由于您有多个带有 $(".vlrTotal") 的元素,因此您需要迭代并为每个元素设置值。当您访问 .val() 方法时,它会按照您的体验获取第一个元素的值。

您需要使用.val( function )

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

使用

$(".vlrTotal").val(function(_, value){
    return formatReal(formatarValor(value));
});

OR,简单的$.fn.each()

$(".vlrTotal").each(function(){
    $(this).val(formatReal(formatarValor($(this).val())));
});

注意:假设您已定义具有所需行为的 formatRealformatarValor 函数。

关于javascript - 将值格式化为 "doesn' t work',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969271/

相关文章:

javascript - 使用 D3.js SVG 的二维多边形 bool 运算

jquery - 使用 jQuery 通过单击链接取消隐藏 div

java - Hibernate原生查询方法

javascript - Rails 5 上的 Turbolinks 和 jQuery 兼容性

javascript - JQuery 与 Angular 实现数百个值 slider

jquery - 如何停用内容编辑

javascript - 句子中间的省略号

javascript - 在 NestJS 中获取 Auth0 用户信息

javascript - Vue js vue cli3 应用程序在 ie11 中不起作用(babel 没有加载 polyfills?)

javascript - 如何计算乘客总数