I'm writing a javascript that checks the user input and validates it as a num开发者_运维问答ber, and this is my function:
<script type="text/javascript">
function checkThis(field)
{
if(isNaN(field.value))
{
alert(field.value + ' is an illegal value. Insert a number');
}
}
</script>
Now I want, when the condition is true, restore the last typed value, for example: if the user types 123
, then the condition is false, but if the user types 123a
then the condition is true and the alert is triggered. I want, after the alert, the value of the field becomes 123.
This is the code of the field:
<input type="text" onkeyup="checkThis(this)" />
Can this be done?
<script type="text/javascript">
var prevValues = []
function checkThis(field)
{
if(isNaN(field.value))
{
alert(field.value + ' is an illegal value. Insert a number');
var prevValue = prevValues[field] || ""
field.value = prevValue
}
else
{
prevValues[field] = field.value
}
}
</script>
function checkThis(field) {
if(isNaN(field.value)) {
alert(field.value + ' is an illegal value. Insert a number');
field.value = field.lastValid || "";
} else {
field.lastValid = field.value;
}
}
Though I would strongly dis-recommend using dialog boxes to inform the user of an input error. It is distracting, irritating and frustrating to be interrupted while you type. Better use something less intrusive like colors or a little icon that appears as the user types.
精彩评论