简体   繁体   中英

How to fix Number.isInteger() function in JavaScript

When I press a button then it retrieve a value from textarea HTML code

<textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea>
<input  name="infoDominio" type="submit"  class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()">

Javascript code

var res = myVar[0];
var ress = 4567891;
var val1 = Number.isInteger(res);
var val2 = Number.isInteger(ress);
document.write(myVar[0]+" "+val1+" "+val2+" "+res);

Where myVar[0] = 4567891; myVar[0] myVar[0] = 4567891; myVar[0] value comes from textarea. But I can't get proper output. I think val1 should be true. Output looks Like this. Would you suggest me how can I get val1=true.

4567891 false true 4567891

textarea will produce a string and not an integer .

You need to parse it as integer :

var res = parseInt(myVar[0]);

As a side note: the user may type a non-integer value in your textarea. Maybe are you looking for input type="number"/> ?

I think this way useful for you

 function add_card(){ myVar = document.getElementById("list_card").value; var res = Number(myVar); var ress = 4567891; var val1 = Number.isInteger(res); var val2 = Number.isInteger(ress); document.write(myVar+" "+val1+" "+val2+" "+res); } 
 <textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea> <input name="infoDominio" type="submit" class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()"> 

只需将val1分配更改为此

var val1 = Number.isInteger(parseInt(res));

Use this regular expression

  • /^ -> start of string
  • \\d+ -> one or more occurrence of digit (\\d)
  • $/ -> end of string

 function add_card(){ var res = document.getElementById('list_card').value; var ress = 4567891; var val1 = /^\\d+$/.test(res); var val2 = /^\\d+$/.test(ress); document.write(res+" "+val1+" "+val2+" "+ress); } 
 <textarea rows="10" cols="17" id="list_card" placeholder="Insert Card Numbers"></textarea> <input name="infoDominio" type="submit" class="btn btn-primary btn-block btn-sm" value="Add Card" onclick="add_card()"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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