开发者

Form Field Verification Not Working

I've got some form verification code that doesn't seem to be working correctly, and I can't figure out why.

function isTextFieldEmpty(textField){
    //return true or false depending on whether or not there is any text in the field

        console.log("Checking to see if the current field is empty...");

    var val = textField.value;          //val is the text from the current field
        console.log("The current value of 'val' is: " + val);
    if(val.length < 1){
        return true;
    }else{
        return false;
    }

}

The error I get is: "Uncaught TypeError: Cannot read property 'length' of undefined". Sure enough, my console log says that the value of 'val' is undefined.

I'm sure I'm missing something, but I'm still learning JS and can't figure out what it is. Any suggestions?


Edit: Here is what I'm passing to the function:

var uName = document.getElementById("unionname");
var noUnionName = isTextFieldEmpty(uName);

'unionname' is the id of the texfield that I'm trying to validate. Here is the relevant HTML:

    <div class="formBox">
        <label for="unionname">Union Name</label>
        <input type="text" name="unionname" i开发者_如何学编程d="unionname" value="" class="wide"/>
        <span class="feedback good">Sample good message</span>
    </div>


You are declaring var val locally in that function. Try declaring it globally by putting it at the top of your script; don't need to set it, just declare it.


I've gotten it working. Seems that the validation function was fine; the problem was in the way I was calling it.

window.onload = justDoIt;

function justDoIt() {

    var uName = document.getElementById("unionname");

    uName.onblur = function(){
        clearMessages(uName);       // clear out old feedback for this field

        var noUnionName = isTextFieldEmpty(uName);

This is how I ended up calling the function.


Ironically, it seems that the faulty .onblur code that I left out of my previous example may have been the cause of my problem. But I'm really not sure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜