简体   繁体   中英

Global Variables not Accessible to Functions Javascript

I am using javascript to validate the information a user has put into a form. I have two functions in my code which both need to check that the information in two text fields is the same. One function is called when the form is submitted, the other when something is typed into the second field.

However neither function seems to be able to access these variables. Google Developer tools shows their value to be Null. The code works fine when I declare the variables within each function but I thought it should be possible to declare them just once

var user1 = document.getElementById('user1');
var user2 = document.getElementById('user2');

function validateText() {
    var message2 = document.getElementById('confirmMessage');  
    if(user1.value !== user2.value) {
        message2.innerHTML = "Your usernames must be the same!";   
        return false;
    }
}

function checkUser() {
    //Store the Confimation Message Object ...
    var message = document.getElementById('confirmMessage');
    //Compare the values in the user field 
    //and the confirmation field
    if(user1.value == user2.value) {
        //The usernames match. 
        // tell the user that they have entered the correct password 
        message.innerHTML = "Passwords Match!"
    }
}

you need to define these variables after the document is loaded.

var user1, user2;
document.onload = function () {
    user1 = document.getElementById('user1');
    user2 = document.getElementById('user2');
}

If the user1 and user2 elements are created by Javascript or by HTML that is placed after the JS (perhaps you are inserting this JS in the head section) then they still dont exist when you first run your script. This means that the getElementById variables will not find anything and return null.

You need to make sure that you call getElementByID after the apropriate elements have been created. ONe easy way to do that is put the calls inside the validation functions but another possibility would be to put it in an onLoad handler.

I would prefer sticking them in the validators though - getting elements by ID is not an expensive operation (so you don't need to worry about performance) and the closer you fetch the data to when you use it the less stuff to worry about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM