1
if(document.form.user.value=='')

这是一个 javascript 代码,用于测试它是否为空输入框,

但我需要一段代码来控制输入框中是否有任何字符?谁能帮助我?

我的意思是任何字符,如 /、& 或任何字母……或者我可以说任何不是数字的字符!

4

3 回答 3

1

Add the negation ! operator to your if statement:

if (!document.form.user.value=='')

Will return true if the value is different than an empty string (that is, if it has any character).

Or simply add an else block to your current if..

if(document.form.user.value=='') {
    //empty value
} else {
    //not empty
}

Updated answer as per question/comment update:

Use a regex to match for non-number characters:

if (/[^\d]/.test(document.form.user.value))
    //contains a non 0-9 character

isNaN is another viable option, but it'd allow for some non 0-9 characters: float . and negative - values would be allowed.

于 2012-06-12T20:21:00.057 回答
1

You mean if there is one or more characters, i.e. not empty?

if (document.form.user.value != '')

or:

if (document.form.user.value.length > 0)
于 2012-06-12T20:21:07.047 回答
0

检查值是否存在:

if($(input).val())

或者:

if($(input).val().length > 0)
于 2012-06-12T20:23:22.193 回答