$('#input5').val(total) 返回输入:157 指定的值"1.234.567"无法解析,或者超出范围?



我的问题与这个问题 stackoverflow.com/questions/61961905/javascript-number-formatting-on-keyup-event 相似,但我在那里找不到答案。

我的代码是这样的:

$('#input2').change(function(){
var format = new Number('1234567').toLocaleString("id-ID");
$('#input4').val(format);
}

而我的 html 是这样的:

<input type="number" class="form-control" id="input2" name="jumlah">
<input type="number" class="form-control" id="input4" name="total" disabled>

结果是:

The specified value "1.234.567" cannot be parsed, or is out of range.

我现在能做什么?

1.234.567

不是有效的数字(从JavaScript的角度来看(,因此不能将其设置为输入type=number的值。问题在于解析这样的数字:它应该被解释为1 234 5671.234567还是1234.567等?

为了使用这种格式,您需要将输入类型更改为text并且一切正常。但请记住,这样做会使值成为文本,因此为了使其成为数字,您需要手动转换它。

您需要将#input4转换为text,因为格式化的数字不是有效的数字。

$(document).ready(function() {
$('#input2').change(function() {
var format = new Number('1234567').toLocaleString("id-ID");
$('#input4').val(format);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="form-control" id="input2" name="jumlah">
<input type="text" class="form-control" id="input4" name="total" disabled>

相关内容

最新更新