简体   繁体   中英

JavaScript global variable not visible inside function

Im trying to use global variables for my js and its like below code

var fullName = document.getElementById("elementId").value;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;

but when I try to use it inside a function function dosen't work .So I just pasted the var fullName into the function and then it works. So please tell me can I assign values into a global variable via document.getElementById("elementId").value; When I try to use nameFormat inside function it works either declare inside or outside. This is the full code

//common js regular expressions
var emailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;

//global variables
var fullName = document.getElementById("jsname").value;
var email = document.getElementById("jsun").value;

function validateForm() {

    //var fullName = document.getElementById("jsname").value;

    //onsubmit full name validation

    if (!(fullName.match(nameFormat))) {
        document.getElementById("pidnamevalidate").innerHTML = "Name should be in a valid format";
        document.getElementById("pidnamevalidate").style.color = 'green';
        return false;

        //onsubmit email validation

    } else {
        return true;
    }
}

It is fine for "nameFormat" to be a global variable, but it looks like you're getting fullName from an editable form field. If you set fullName outside of the validateForm function then you are setting it to the initial value of the field (or as @RobG mentioned, possibly trying to get the value of an element that doesn't yet exist in the DOM which would result in an error). Setting fullName inside validateForm will get its value at that point in time which I assume is what you want.

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