简体   繁体   中英

Passing parameters from JavaScript

I have the typical HTML "contact me" page, ie name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven

You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.

You'd have a javascript function something like this:

function check_it_all() { 
  if (all_ok) {
     return true;
  } else {
     return false;
  }
}

And the form

<form action=.....  onsubmit="return check_it_all();">
....
</form>

Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here .

You should still use the submit button to submit the form, that is the correct behavior.

Input validation should be done using the <FORM> 's onSubmit event. It should look something like this:

<script>
    function validate() {
        var isFormValid = whatever; // validate form
        return isFormValid;
    }
</script>

<form action="your.php" method="POST" onSubmit="return validate()">
    <!---fields--->
</form>

The function validate() returns a bool . This will stop the submission if validate() returns false.

<input type="submit" onclick="return validate()" value="click" />

I am an aspx.net developer so I am used to putting the validation call on the button.

If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.

Such as

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

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