Search code examples
javascriptfunctionvariablesdeclare

How do I declare variables for multiple functions


Correct me if I am wrong, but isn't it possible to declare a variable right after the script tag, so that it can be used throughout that script? I tried this, and my functions are acting as if it isn't even there. Did I do something wrong, or is this supposed to happen. I would hate to have to redeclare all of my variables for each function if they are the exact same thing.

Sorry about that

<script>
  var na=document.getElementById('nr');
  var ea=document.getElementById('er');
  var em=document.subscribe.email;
  var fn=document.subscribe.fname;
  var ln=document.subscribe.lname;
  var eml=document.subscribe.email.value.length;
  var fnl=document.subscribe.fname.value.length;
  var lnl=document.subscribe.lname.value.length;
  var at=document.subscribe.email.value.indexOf("@");
  var per=document.subscribe.email.value.lastIndexOf("."); 

function validate_form() {
  if((fnl<1 || lnl<1) && !eml<1){
      alert("Please enter your first and last name.")
      if(fnl<1){fn.focus()}else{ln.focus()}
      }
  else if((fnl<1 || lnl<1) && eml<1){
      alert("Please fill in all fields.")
      if(fnl<1){fn.focus()}else{ln.focus()}
      }  
  else if(eml<1 || at<1 || per-at<2 || eml-per<2){
      alert("Please enter a valid email address")
      em.focus()
      }    
  else if (at>1 && per-at>2 && eml-per>2 && fnl>1 && lnl>1){return true}
  vfn(); vln(); vem();
 return false}

It works perfectly fine when the vars are INSIDE the function, but when they are like this, nothing at all happens.


Solution

  • I actually figured out how to do it. I just read about the global variables, and how to declare them inside a function. So I put all the vars back inside the function, erased the "var" on it and it works perfect now.

    function validate_form() {
       na=document.getElementById('nr');
       ea=document.getElementById('er');
       em=document.subscribe.email;
       fn=document.subscribe.fname;
       ln=document.subscribe.lname;
       eml=document.subscribe.email.value.length;
       fnl=document.subscribe.fname.value.length;
       lnl=document.subscribe.lname.value.length;
       at=document.subscribe.email.value.indexOf("@");
       per=document.subscribe.email.value.lastIndexOf("."); 
      if((fnl<1 || lnl<1) && !eml<1){
          alert("Please enter your first and last name.")
          if(fnl<1){fn.focus()}else{ln.focus()}
          }
      else if((fnl<1 || lnl<1) && eml<1){
          alert("Please fill in all fields.")
          if(fnl<1){fn.focus()}else{ln.focus()}
          }  
      else if(eml<1 || at<1 || per-at<2 || eml-per<2){
          alert("Please enter a valid email address")
          em.focus()
          }    
      else if (at>1 && per-at>2 && eml-per>2 && fnl>1 && lnl>1){return true}
      vfn(); vln(); vem();
     return false}