Check if multiple functions are true, then do something

37,691

Solution 1

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...

Solution 2

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

Share:
37,691
Siriss
Author by

Siriss

I am a sys admin getting going in the iOS world. I love to learn, and help others. SOreadytohelp

Updated on July 09, 2022

Comments

  • Siriss
    Siriss almost 2 years

    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!

  • nico
    nico over 13 years
    Forgetting about the syntax error, what's the point of having three functions if they are all the same?
  • Basic
    Basic over 13 years
    @nico I'm guessing they're not - the "condition" will vary in each.
  • Basic
    Basic over 13 years
    I'd also suggest that you start using alert() commands in your JS to work out what is running (or use the firebug addon in firefox for a full JS debugger)
  • T.J. Crowder
    T.J. Crowder over 13 years
    @Basiclife: "I'd also suggest that you start using alert() commands in your JS..." God no, there is no longer any excuse for debug-via-alert. Use Firebug (as you mentioned), or Chrome's Dev Tools, or Visual Studio, or ... :-) +1 for the form thing, I didn't even look at the HTML.
  • Siriss
    Siriss over 13 years
    @Basiclife: that will not work because my Javascript function checknewaccount() does not call the accountcode.php file. I want to have the javascript confirm all the fields are correct and then submit the form to accountcode.php. I used return checknewaccount() on the submit button so it would only submit if checknewaccount returns true. I have used this in the past with something like the following....
  • Basic
    Basic over 13 years
    @T.J. Crowder I agree that leaving an alert in production code is a huge no-no - and in my own code I always have a div with id="log" and a debug(message) function which outputs to it - which allows me to see a nice log of events/commands - but as a quick and dirty method of seeing if a function is called, I still think it's useful. I acknowledge that this is a controversial view point
  • Basic
    Basic over 13 years
    @Siriss - The form will only submit if the method referenced in the onsubmit="" returns true - so this is exactly the place to put validation. If the method returns false, nothing happens.
  • Basic
    Basic over 13 years
  • Siriss
    Siriss over 13 years
    <input type="submit" onclick="return confirmsubmit()"/> function confirmsubmit(){ var submit = confirm("confirm this"); if(submit) { return true; } else { return false;} } When confirmsubmit() returns true, the form submits, otherwise it does not. Am I missing something for this though? I do use firebug and Chrome debug, but could not find it with this... I appreciate the help!
  • Basic
    Basic over 13 years
    @Siriss - No worries, I understand what you're doing and it is similar to what I'm suggesting - The only difference is that you're assuming that the form will be submitted via that button (true at present but may change in future) - If the validation is on the form not the submit button, it applies in a far wider set of circumstances and is therefore easier to maintain. What you should've done in firebug is put a breakpoint on your checknewaccount() function and see if it's being called. Assuming it is, check the Net tab to see if a new URL is requested - If so, this page is fine...
  • Basic
    Basic over 13 years
    @Siriss (Cont) If not, thi page has a problem (probably in the HTML). Does your function get called? If so, what does it return? Try replacing your whole checknewaccount() function body with a simple return true or return false and see if it works as expected - then you can determine if it's your JS at fault or something else...
  • Siriss
    Siriss over 13 years
    @T.J. Crowder: return emailvalid()&& checkname() && passwordcheck(); was successful! Thank you very much!
  • Siriss
    Siriss over 13 years
    The solution was using return emailvalid()&& checkname() && passwordcheck(); as T.J Crowder suggested below, instead of if(emailvalid()&& checkname() && passwordcheck()). Thank you again for your help!
  • Basic
    Basic over 13 years
    Interesting - The syntax provided by TJ is more succinct and elegant but is functionally identical to your own code - unless I'm missing something ?
  • Siriss
    Siriss over 13 years
    Yeah I don't quite get it either. I am going to do much more testing to try and figure out why. If anyone has some ideas please post!
  • Basic
    Basic over 13 years
    @Siriss not a problem - and welcome to Stack Overflow :) I hope you like it here. For what it's worth, I'm a little confused as to why that made a difference - see my comments on TJs answer. I'd still strongly recommend you consider validating at the form level rather than the submit button level though - it may save you work in future.
  • Siriss
    Siriss over 13 years
    I have switched it to validating on the form level. That also seems more secure. Thanks for that tip.
  • Basic
    Basic over 13 years
    Welcome - Needless to say, if you get any more issues, ask on SO :)
  • Siriss
    Siriss over 13 years
    Ok- I cannot get it to return anything but true, even if all the other functions are returning false. Is there another way to get the values of the function returns and check that they are true? I am stumped. It is submitting now with the return emailvalid() && checkname() && passwordcheck();.... maybe I need to start over.
  • T.J. Crowder
    T.J. Crowder over 13 years
    @Siriss: The syntax is correct, there must be some other issue in your code. I've updated the above to provide a simple example of what it looks like you're trying to achieve, with live working copies.
  • Basic
    Basic over 13 years
    Ok, I've mocked up your code and posted a fully tested version above with only a single restriction - the form will only submit if the textbox contains the value test. It's simplistic but should give you a starting point
  • Basic
    Basic over 13 years
    Oh and just another thing I've noticed - checknewaccount, checkname, etc - shouldn't it be checkpassword not passwordcheck? :)
  • Basic
    Basic over 13 years
    @TJ +1 for an exhaustively detailed answer - very good points especially the bits about xhtml - Now I know how you got the 35k :)
  • Siriss
    Siriss over 13 years
    Yes it should, but that was an error on my part when I was making the post. The code I have is correct. I have learned a lesson and I am going to work on posting the functions completely now even thought they are long and ugly. I am also going to read through all this that was posted overnight!
  • Siriss
    Siriss over 13 years
    I think you are right. I have a feeling it has to do with my return statements based on all you have written. I am going to sift through it all and get back now. Thanks for spending the time!
  • Siriss
    Siriss over 13 years
    Ok thank you all guys. I have it figured. The return emailvalid() && checkname() && passwordcheck(); worked because if one function returned true, it would assume true and submit. When I changed that back to the if statement it broke. It was a combination of my returns and my handlers and running the check onSubmit(). Thank you guys for all the time. The code examples from both were a huge help. I wish I could check two answers! Thanks again!
  • Siriss
    Siriss over 13 years
    I really appreciate the code samples. They were a huge help. I have posted a brief description of what went wrong up above. Thanks again!
  • T.J. Crowder
    T.J. Crowder over 13 years
    @Siriss: "The return emailvalid() && checkname() && passwordcheck(); worked because if one function returned true, it would assume true and submit." No, JavaScript doesn't work that way. && means and. So if emailavoid() returned true but checkname() returned false, the result would be false, not true.
  • Basic
    Basic over 13 years
    @Siriss: I have to say I agree with TJ - If the first return were false, it wouldn;t bother evaluating the 2nd as the result is irrelevant but for an AND (&&) it should keep evaluating until it finds a negative (conversely, OR will continue until it finds a positive)
  • Siriss
    Siriss over 13 years
    Hey guys. I certainly understand the difference between the && and || statements, but I do not understand how changing that if() statement to that one line of code would make the form submit. It did not submit correctly, but it submitted (when it was not before) with just that one change. I thought it would work like Java and how you guys are explaining above. I only ask to try and better understand Javascript and see where else I was going wrong. I am most likely missing something else. I really appreciate all the help you guys have given.
  • Siriss
    Siriss over 13 years
    So I am still confused about how this solution worked, but it has helped me narrow down the root of the problem now. I have created a new post stackoverflow.com/questions/4434470/… with the code and description, which you are already familiar with. Thanks again and I am finding that Stackoverflow is the best there is.