Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple functions are true, then do something

I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:

function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
    return true;
}
else{
    return false;
}
}


function emailvalid()
{
      if(email condition)
      {
          return true;
      }
      else {
          return false;
      }
}

function checkname())
{
      if(name condition)
      {
          return true;
      }
      else {
          return false;
      }
}

function passwordcheck(){
      if(password condition)
      {
          return true;
      }
      else {
          return false;
      }
}

html below:

<form  id="newaccount" name="newaccount" method="post"  onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password"  onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>

When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.

To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?

I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!

like image 364
Siriss Avatar asked Dec 12 '10 21:12

Siriss


2 Answers

you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...

<form action="accountcode.php" id="newaccount" name="newaccount" method="post"  onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password"  onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>

Fully tested code:

<html>
    <head>
        <script type="text/javascript">
        function checknewaccount() {
            return emailvalid() && checkname() && passwordcheck();
        }

        function emailvalid() {
             var emailAddress = document.getElementById('email').value;
             return (emailAddress=='test');
        }

        function checkname() {
             return true;
        }

        function passwordcheck() {
             return true;
        }

        </script>
    </head>
    <body>
    <form action="#" onsubmit="return checknewaccount();">
        <input type="text" id="email" name="email"/>
        <input type="submit"/>
    </form>
    </body>
</html>

The form in the above code will only submit if the textbox has a value of test

A slightly better implementation would be:

<html>
    <head>
        <script type="text/javascript">
        function checknewaccount() {
            if(emailvalid() && checkname() && passwordcheck()) {
                return true;
            } else {
                document.getElementById('validation').innerHTML = 'Validation failed!';
                return false;
            }
        }

        function emailvalid() {
             var emailAddress = document.getElementById('email').value;
             return (emailAddress=='test');
        }

        function checkname() {
             return true;
        }

        function passwordcheck() {
             return true;
        }

        </script>
    </head>
    <body>
    <div id="validation"></div>
    <form action="#" onsubmit="return checknewaccount();">
        <input type="text" id="email" name="email"/>
        <input type="submit"/>
    </form>
    </body>
</html>

As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...

like image 167
Basic Avatar answered Sep 20 '22 22:09

Basic


This part's fine (I took the liberty of fixing the indentation):

function checknewaccount(){
    if(emailvalid()&& checkname() && passwordcheck())
    {
        return true;
    }
    else{
        return false;
    }
}

Although you could improve it:

function checknewaccount(){
    return emailvalid() && checkname() && passwordcheck();
}

This part is a syntax error (to put it mildly):

function emailvalid(), checkname(), passwordcheck(){
if(condition){
    return true;}
else{return false;}

If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)

The same sort of thing is true for your functions in the form:

function emailvalid()
{
      if(email condition)
      {
          return true;
      }
      else {
          return false;
      }
}

That's fine (assuming that email condition is still psuedocode), but there's no need for the if:

function emailvalid()
{
    return email condition;
}

In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.

Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:

HTML:

<form action="http://www.google.com/search"
      method="GET" target="_blank"
      onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password"  onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>

Notes on that:

  • As Basiclife pointed out, your form code has issues. Those are fixed above.
  • Above I've used action="http://www.google.com/search" but of course for you it would be action="accountcode.php" (or at least, I think it would).
  • Use onsubmit for the form submission handler, not onclick on the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
  • In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
  • Only one of the fields above has a name attribute; none of yours do. Only fields with name attributes get submitted with forms. I've only used one name for my example because I only want to submit one field to Google, but for your purposes, you're going to want name attributes on all three fields. This brief article has a discussion of id vs. name and what they're for. You sometimes want both.
  • I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
  • However, I've removed the / from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
  • With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.

JavaScript:

function checknewaccount() {
  return emailvalid() && checkname() && passwordcheck();
}

function emailvalid() {
  var element;
  
  // Get the email element
  element = document.getElementById('email');
  
  // Obviously not a real check, just do whatever your condition is
  return element.value.indexOf('@') > 0;
}

function checkname() {
  var element;
  
  // Get the username element
  element = document.getElementById('username');
  
  // Obviously not a real check, just do whatever your condition is
  return element.value.length > 0;
}

function passwordcheck() {
  var element;
  
  // Get the username element
  element = document.getElementById('password');
  
  // Obviously not a real check, just do whatever your condition is
  return element.value.length > 0;
}

Live copy

Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:

HTML:

<form action="http://www.google.com/search"
      method="GET" target="_blank"
      onsubmit="return checknewaccount()">
<label>Email:  
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password"  onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>

JavaScript:

function checknewaccount() {
  var result;
  // Because we're actually doing something in each of the
  // three functions below, on form validation we want to
  // call *all* of them, even if the first one fails, so
  // they each color their field accordingly. So instead
  // of a one-liner with && as in the previous example,
  // we ensure we do call each of them:
  result = emailvalid();
  result = checkname() && result;
  result = passwordcheck() && result;
  return result;
}

function emailvalid() {
      var element, result;
  
  // Get the email element
  element = document.getElementById('email');
  
  // Obviously not a real check, just do whatever your condition is
  result = element.value.indexOf('@') > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function checkname() {
  var element, result;
  
  // Get the username element
  element = document.getElementById('username');
  
  // Obviously not a real check, just do whatever your condition is
  result = element.value.length > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function passwordcheck() {
  var element, result;
  
  // Get the username element
  element = document.getElementById('password');
  
  // Obviously not a real check, just do whatever your condition is
  result = element.value.length > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function updateLabel(node, valid) {
  while (node && node.tagName !== "LABEL") {
    node = node.parentNode;
  }
  if (node) {
    node.style.color = valid ? "" : "red";
  }
}

Live copy

like image 39
T.J. Crowder Avatar answered Sep 20 '22 22:09

T.J. Crowder