Jquery return empty/null 如果值为 nan

Jquery return empty/null if value is nan

我有一个表格,如果用户输入数字,输出将是十进制的(这项工作)。 我想要的是,如果用户没有在字段 A 中键入值,而是使用 Tab 按钮转到字段 B,则字段 A 仍然为空白而不是 NAN。或者如果用户在字段 A/B 中键入然后删除它,该字段中的值将是空白而不是 return 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('');
   }

您的 on blur 事件导致 issue.Check 值在将其分解为浮点数之前不是 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
      });
  }
})

您可以添加一个额外的条件,即:$(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" />

$('.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" />