Javascript提示/文本框只有数字 [英] Javascript prompt/textbox only numbers
问题描述
嘿,我只是学习javascript,我有一些html和css的背景。
我不知道如何只允许数字值输入提示,或检查它的一个数字还是不是重新提示如果没有。
您已经有了一个很好的答案。
假设您的号码字段如下所示:
code>< input type =textname =num_fldid =num_fldonchange =return chkNum(); />
<$ p $ p>
function chkNum()
{
var rc = false;
if(!isNaN(parseFloat(n))&& isFinite(n))
{
rc = true;
}
else
{
document.getElementById(num_fld)。value = 0;
}
return rc;
}
此函数检查数字是否真的是一个数字,与输入,所以坏的值不停留在原地。 Offhand我不太确定如果返回false阻止数字被输入(类似在验证函数。)我相信从我的测试,返回false确实影响了在字段中,但我不是100%确定。
您也可以在失败时更改输入字段的背景和/或文本颜色(测试的else部分,因此用户注意到错误。 code> alert(); 适合测试,但会混淆您的网站在生产中的外观。
Hey guys I'm just learning javascript, I have some html and css background though.
I can't figure out how to allow only number values to be entered into a prompt, or check if its a number or not than re prompt if its not. Also the same goes for a textbox.
You already have a good answer. This answer is another look at things you can do.
Assuming your number field is like the following
<input type="text" name="num_fld" id="num_fld" onchange="return chkNum();" />
and you've defined a javascript function like so
function chkNum()
{
var rc = false;
if(!isNaN(parseFloat(n)) && isFinite(n))
{
rc = true;
}
else
{
document.getElementById("num_fld").value = 0;
}
return rc;
}
This function checks to see if the number is really a number, but also monkeys with the input, so the bad value does not stay in place. Offhand I am not quite sure if returning false prevents the number from being entered (kind of like in a validate function.) I believe from my testing that returning false does affect what is in the field, but I am not 100% sure of that.
You could also alter the background and/or text color of the input field upon failure (the else part of the test, so the user notices something is wrong. alert();
is good for testing, but kind of messes up the look of your site in production.
这篇关于Javascript提示/文本框只有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!