简体   繁体   English

使用 jQuery 更改输入文本值(如果它是 NaN)

[英]Change input text value if it is NaN using jQuery

I want to change value of textbox to -999, if it is having a value of NaN.如果文本框的值为 NaN,我想将文本框的值更改为 -999。 I have written some code but it is not working, please suggest me what I need to change in this.我已经写了一些代码,但它不起作用,请建议我在这方面需要改变什么。

 if($('input[name="tt10"]').val() === NaN) { $('input[name="tt10"]').val('-999'); }
 <input name='tt10' value='NaN'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You need to call .val() to get the value of the input.您需要调用.val()来获取输入的值。 And since the value is a string, you need to compare it with a string.由于该值是一个字符串,您需要将它与一个字符串进行比较。

 if($('input[name="tt10"]').val() === 'NaN') { $('input[name="tt10"]').val('-999'); };
 <input name='tt10' value='NaN'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You have to use .val() to get value from input field .您必须使用.val()input field获取值。
Like this:像这样:

$('input[name="tt10"]').val()

And with that value now, you can check if value of input is NaN or not:现在使用该值,您可以检查输入的值是否为NaN

if($('input[name="tt10"]').val() === 'NaN') {
    $('input[name="tt10"]').val('-999');
};

For more information you can visit official documentation .有关更多信息,您可以访问官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM