如何检查输入是否为数字并相应地调用函数? [英] How to check if input is a number and call a function accordingly?
本文介绍了如何检查输入是否为数字并相应地调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面输入我的代码.我需要对其进行修改,以便检查输入是否为数字.如果输入的不是数字,则必须显示一条消息,请仅输入数字".如果输入为数字,则必须调用compare()函数.我尝试了多种方法,包括使用isNAN,但似乎无济于事.有人可以在这里提供帮助吗?
I have my code below..I need to modify it so that the input is checked if it is number.If its not a number, then a message has to be displayed as follows " please enter only nos". If input is a number,then function compare() has to be called.I tried many ways including using isNAN but nothing seems to work.Can anyone help here please?
<head>
<title>Guessing Game</title>
<meta charset = "utf-8">
<script>
<!--
var num_guess=0;
function chkinput()
{
if (!isNaN(parseFloat(obj)) && isFinite(obj);)
{
compare();
}
else
{
alert("Please enter only numbers");
return false;
}
}
function compare()
{
var generated_num = document.getElementById( "target" );
var entered_num = document.getElementById( "userguess" );
if ( parseInt( entered_num.value ) > generated_num.value )
window.alert("Too high. Try again!");
else if ( parseInt( entered_num.value ) < generated_num.value )
window.alert("Too low. Try again!");
else
{
window.alert("Congratulations!You guessed the number!");
if ( parseInt( num_guess ) < 10 )
window.alert( "Either you know the secret or"
+ " you got lucky!");
if ( parseInt( num_guess ) == 10 )
window.alert( "Ahah! You know the secret!" );
if ( parseInt( num_guess ) > 10 )
window.alert(
"You should be able to do better!" );
guess.userguess.value ="";
window.status= "Done";
random();
} // end else
num_guess++;
} // end function compare
function random() // function to generate a random no between 1 and 1000
{
document.getElementById( "target" ).value =
Math.floor( 1 + Math.random() * 1000 );
} // end function random
// -->
</script>
</head>
<body onload = "random()">
<form id = "guess" action = "">
<div>
Guess a number between 1 and 1000:
<input type = "text" id = "userguess" /><br />
<input type = "button" value = "Guess"
onclick = "chkinput()" />
<input type = "hidden" id = "target" value = "0" />
</div>
</form>
推荐答案
您可以这样尝试:
if (!isNaN(parseFloat(obj)) && isFinite(obj);)
{
compare();
}
else
{
alert("Please enter only numbers");
return false;
}
这篇关于如何检查输入是否为数字并相应地调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文