简体   繁体   中英

How do I validate form and send input values with ::mailto with Javascript?

I have a form in which I want to:

  • Validate with JavaScript
  • When the validation is done, I want to "sort" of make a callback function much like sendMail(); function (See code example below).

To make my question more clear, what I want is to "mix" the onclick and onsubmit functions so that the Validation() function calls. And when it validates the page, then I want to call the sendMail() function.

Any ideas? Thank you beforehand!

Code:

Fiddle

HTML:

<form method="POST" action="index.php" onsubmit="return Validate()" name="vForm">

            <div>
                <input id="name" type="text" name="username" class="textInput" placeholder="Username">
                <div id="name_error" class="val_error"></div>
            </div>

            <div>
                <input type="submit" class="btn" name="register" value="Register">
            </div>

        </form>

JS:

    var username = document.forms["vForm"]["username"];

         function Validate(){
            // VALIDATE USERNAME
            if(username.value == ""){
                name_error.textContent = "Username is required";
                username.style.border = "1px solid red";
                username.focus();
                return false;
            }

// ADD EVENT LISTENERS
    function nameVerify(){
        if (username.value != "") {
            name_error.innerHTML = "";
            username.style.border = "1px solid #110E0F";
            return true;
        }
    }

HTML - sendMail(); :

<textarea id="myText">
    Text that will be sent to body of email.
</textarea>

<button onclick="sendMail(); return false">Send</button>

JS - sendMail(); :

function sendMail() {
        var link = "mailto:example@mail.com"
                 + "?cc=myCCaddress@example.com"
                 + "&subject=" + escape("This is my subject")
                 + "&body=" + escape(document.getElementById('myText').value)
        ;

        window.location.href = link;
    }

suggest use the jquery plugin

Validation

and the callback function you can use the submitHandler.

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