abdelelbouhy Posted May 2, 2009 Share Posted May 2, 2009 function isInt() {var newValue = document.ccForm.number.value;var extraChars=" ";var search;for(i=0; i != newValue.length;i++ {aChar = newValue.substring(i ,i+1);search = extraChars.indexOf(aChar);if(search == -1 && (aChar < "0" || aChar > "9")) {return false;}}return true;the function is working properly but i'm bit confused with the search var it's set up to search for spaces in the number what i want know how the search is bigger than -1 and it should be -1 if there isn't spacesplease help Link to comment Share on other sites More sharing options...
jeffman Posted May 2, 2009 Share Posted May 2, 2009 I posted some stuff earlier, but I like these better. First we have an isInt() function, and you can pass it anything (number, string, array, undefined variable) and get the correct response: a Boolean true or false. That is, a true integer returns true, and a string containing an integer returns true. An empty string returns false. function isInt (n) { if (typeof n == "number") { return (parseInt(n) == n) } else if (typeof n == "string") { if (n.length) { return !n.match(/\D/); } } return false;} If anyone has the need, here's a way to do it by re-prototyping both the Number and the String objects. // Put these statements in your global spaceif (!Number.prototype.isInt) { Number.prototype.isInt = function () { return (parseInt(this) == this); }}if (!String.prototype.isInt) { String.prototype.isInt = function () { if (this.length) { return !this.match(/\D/); } return false; }} Use them like this: n = 3;if (isInt(n) ) { // it's an int}n = 9;if (n.isInt() ) { // it's an int}s = "7";if (s.isInt() ) { // it's an int} FWIW: parseInt() and Number() don't mind if the argument has blank spaces before or after the number characters, so a thing like " 5 " gets parsed as 5. The way I used those functions originally meant that my earlier functions allowed such a string to pass the test. The revised versions (what you see above) do not. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.