waltweave waltweave - 4 months ago 9
Javascript Question

Why is my for loop in JavaScript causing my webpage to freeze?

I am currently working on a project, and I need to make an alert box pop up if the user inputs a value that is not a number. I created a for loop to do this and it works, however whenever I type in something that is not a number, my webpage freezes and I have to close it. I can't figure out what I am doing wrong. Here's the code that I have.

var Y=1

for(var i = 0; i < Input.length; i++)
{
if(isNaN(Input.charAt(i)))
{
alert("Parameter is Not A Number");
Y = 0;
}
}

Answer

If you are using HTML5 you can limit user input to numeric values by simply specifying

<input type="number">

Try this if you want to stick to alert box and stuff

<input type="input" id="edit1"/>

Js

$(document).ready(function(){
    $('[id^=edit]').keypress(validateNumber);
});

var Y=1

function validateNumber(event) {
 var key = window.event ? event.keyCode : event.which;
 if ( key < 48 || key > 57 ) {
      alert("Parameter is Not A Number");
      Y = 0;
    }
    else return true;
};