【问题标题】:Jquery return empty/null if value is nan如果值为 nan,则 Jquery 返回空/null
【发布时间】:2021-04-29 21:37:54
【问题描述】:
我有一个表格,如果用户键入数字,输出将是十进制的(这项工作)。
我想要的是,如果用户没有在字段 A 中键入值,并使用 Tab 按钮转到字段 B,则字段 A 仍然是空白而不是 NAN。或者如果用户在字段 A/B 中键入然后删除它,则该字段中的值将是空白而不是返回 0/NAN。请帮帮我
$('.Currency').keyup(function(){
// value is either the inputed numbers or 0 if none
let val = parseFloat($(this).val());
if (isNaN(val)) {
$(this).val('');
}
});
$('input.Currency').on('blur', function() {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
field A
<input class="numeric Currency" type="text" />
field B
<input class="numeric Currency" type="text" />
我试试这个,但它仍然给我一个 NaN
if (isNaN(val)) {
$(this).val('');
}
【问题讨论】:
标签:
javascript
jquery
decimal
nan
【解决方案1】:
您可以添加一个额外的条件,即:$(this).val().trim() != "" 如果是,则只更改其值。
演示代码:
$('input.Currency').on('blur', function() {
//check if val is not ""
if ($(this).val().trim() != "" && !isNaN($(this).val())) {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
} else {
$(this).val("")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
field A
<input class="numeric Currency" type="text" /> field B
<input class="numeric Currency" type="text" />
【解决方案2】:
您的 on blur 事件导致了问题。在将其解析为浮点数之前检查值不是 NaN。
$('.Currency').keyup(function(){
// value is either the inputed numbers or 0 if none
let val = parseFloat($(this).val());
if (isNaN(val)) {
$(this).val('');
}
});
$('input.Currency').on('blur', function() {
const value = this.value.replace(/,/g, '');
if(!isNaN(parseFloat(value))) { // ADD THIS
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
}
})
【解决方案3】:
$('.Currency').keyup(function(){
// value is either the inputed numbers or 0 if none
let val = parseFloat($(this).val());
if (isNaN(val)) {
$(this).val('');
}
});
$('input.Currency').on('blur', function() {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
field A
<input class="numeric Currency" type="text" />
field B
<input class="numeric Currency" type="text" />