I have a textarea where a user can insert some text, and after it hits the "Send" button, the text should be copied (as it was entered) in the default email window (I have tried with Outlook).
For now, if I want to enter:
abcd
def
I will get the output:
abcd</br></br>def
This is the html file:
<div class="form-group">
<label for="message" class="sr-only">Message</label>
<textarea name="message" id="message" class="form-control" cols="30" rows="7" placeholder="Message" minlength="5" data-validation-minlength-message="Min 5 characters" maxlength="999" required></textarea>
</div>
<div class="form-group">
<input type="submit" value="Send Message" onclick="javascript: sendemail();" class="btn btn-primary" id="abcd">
</div>
And this is the .js file:
function sendemail() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message2 = document.getElementById('message').value;
var myLineBreak = message2.replace(/\r\n|\r|\n/g, "</br>");
var pattern = /[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*/;
if (name.length == 0)
alert("Please complete the Name field!");
else
if (pattern.test(String(email).toLowerCase()) == 0)
alert("Please enter a valid email address!");
else
if (message2.length < 5)
alert("Message too short!");
else {
document.getElementById("form1").action = "mailto:JustinF#somesite.com&body=" + myLineBreak;
document.getElementById("form1").submit();
}
}
I've tried also to add this to style.css:
#abcd {
white-space: pre-wrap;
}
but with no luck... ('abcd' is the id of the "Send" button)
I managed to figured it out.
I replaced
var myLineBreak = message2.replace(/\r\n|\r|\n/g, "</br>");
with
var myLineBreak = message2.replace(/\r\n|\r|\n/g, "%0D%0A");
Now it works perfectly.
Related
I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
I have a search form on every page of my website which works perfectly, when submitting the form it goes to a page called search.php..
I have the same form also on my contact page where i also have a contact form.
the contact form does not have a submit button because i use ajax to send the post variables to a contact_process.php page. The contact form is working perfectly however on this page the search form does not work.. When I press the submit button on the search form it just refreshes the whole contact page instead of going to the search.php page. can anyone help? thanks.
The javascript and ajax for contact form:
document.getElementById('submit_message').addEventListener('click', sendMessage, false);
function sendMessage(){
$('#submit_message').removeClass("point_finger_animation");
$('#pointing_finger').fadeOut();
xmlhttp = createXHR();
xmlhttp.onreadystatechange = callback;
var not_valid_email = false;
var your_name = document.getElementById("your_name").value;
var captcha_code = document.getElementById("captcha_code").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var mobile_number = document.getElementById("mobile").value;
if(mobile_number.length < 10 || mobile_number.length > 14){
var not_valid_mobile = true;
}
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length){
var not_valid_email = true;
}
var message = document.getElementById("message").value;
xmlhttp.open("POST", "contact_process.php" ,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if((your_name == "" || your_name == null) || (not_valid_mobile) || (not_valid_email) || (message == "" || message == null)){
$('#container_wrapper').scrollTop(0);
document.getElementById("form_results").innerHTML = "<p>Message not sent!</p>";
if(your_name == "" || your_name == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}else if(not_valid_email){
document.getElementById("form_results").innerHTML = "<p>The email address you entered is invalid!</p>";
}else if(not_valid_mobile){
document.getElementById("form_results").innerHTML = "<p>The mobile number you entered is invalid!</p>";
}else if(message == "" || message == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}
}else{
xmlhttp.send("your_name=" + your_name + "&email=" + email + "&mobile=" + mobile_number + "&subject=" + subject + "&message=" + message + "&captcha_code=" + captcha_code);
}
}
function callback(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
refreshCaptcha();
document.getElementById("form_results").innerHTML = xmlhttp.responseText;
$('#container_wrapper').scrollTop(0);
}
}
html for contact form
<section id="form_area" class="content_box">
<div id="form_results"></div>
<form id ="contact_form" method="post" action="">
<label>Your Name (required)</label>
<input id="your_name" name="your_name" type="text" placeholder="Your Name" onfocus = "checkEnter()">
<label>Your Email (required)</label>
<input id="email" name="email" type="email" placeholder="Email" onfocus = "checkEnter()">
<label>Mobile Number (required)</label>
<input id="mobile" name="mobile" type="text" placeholder="Mobile Number" onfocus = "checkEnter()">
<label>Subject</label>
<input id="subject" name="subject" type="text" placeholder="Subject (Optional)" onfocus = "checkEnter()" >
<label>Your Message (required)</label>
<textarea id="message" name="message" rows="4" type="text" placeholder="Please leave your message here" onfocus = "checkEnter()"></textarea>
<label>Please enter the Captcha below (required). Letters are not case sensitive.</label>
<div id="captcha_wrapper">
<img id="captcha" src="/finalne2/securimage/securimage_show.php" alt="CAPTCHA Image" />
<span id="captcha_refresh"><i class="fa fa-refresh"></i></span>
</div>
<input id="captcha_code" type="text" name="captcha_code" size="10" maxlength="6" onfocus = "checkEnter()" onblur = "checkFields()"/>
<div id="submit_area">
<div id="submit_message" class="menu_level_1 button_style">Send</div>
<div id="pointing_finger"><i class="fa fa-hand-o-left"></i></div>
</div
</form><!--End of contact_form-->
</section><!--End of form_area-->
html for search form:
<div id="search_wrapper" class="menu_level_1">
<div id="search_box">
<form action="search.php" method="get">
<input id="search_content" placeholder="Search website" type="text" name="query" size="40" value="" action="" columns="2" autocomplete="off" delay="1500">
<button id="submit_search" type="submit"><i class="fa fa-search"></i></button>
<input type="hidden" name="search" value="1">
</form>
</div>
</div>
Update:
#Malk thanks for spotting the missing bracket in the closing div of the contact form :) that was indeed the problem :)
Just a guess but maybe try specifying an explicit action attribute in the contact form.
<form id ="contact_form" method="post" action="some_page_here">
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}
I am adding username and email to the userlist and validating email when adding. Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working..
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
<script type="text/javascript">
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
</script>
<style>
.errorclass{
border:1px red solid;
}
</style>
Each time there is a validation error you add 'errorclass' to the email class. So the second time is "errorclasserrorclass" that is not defined in the css.
Use:
email.setAttribute('class','errorclass')
This seems repeated question but please take a look and try to answer.
My javascript validation function is not working.
Javascript code is given below:
<script type="text/javascript">
var ck_name = /^[A-Za-z ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}
(?:\. [a-z]{2})?)$/i
var ck_mobile = /^[0-9]{10}$/;
var ck_address = /^[A-Za-z0-9-,]{40,100}$/;
function validate(myform){
var name = myform.fullname.value;
var email = myform.email.value;
var mobile = myform.mobile.value;
var address = myform.address.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "Enter valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(mobile)) {
errors[errors.length] = "Enter valid 10 digit mobile number .";
}
if (!ck_password.test(address)) {
errors[errors.length] = "You must enter a valid address min 40 char.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valid Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
I have two button 1)submit and 2)cancel
I want when i click submit button,validate function will call and when i click cancel it goes to back to the page.
HTML form
<form action="addorder.php" method="post" enctype="multipart/form-data" name="myform" >
<!-- Form -->
<div class="form">
<?php
if(isset($_SESSION['msg']))
{
?>
<div class="msg msg-ok"><strong><?php echo $_SESSION['msg'];?></strong></div>
<?php } ?>
<label>Full name<span>(Required Field)</span></label>
<input type="text" name="fullname"class="field size1"/>
</p>
<p>
<label>Email<span> (Required Field)</span>
<input type="text" class="field size1" name="email"/>
</label>
</p>
<p>
<label>Mobile<span>(Required Field)</span>
<input type="text" class="field size1" name="mobile"/>
</label>
</p>
<p>
<label>Address<span>(Required Field)</span>
<textarea class="field size1" name="address" rows="3" cols="10"> </textarea>
</label>
</p>
</div>
<!-- End Form -->
<!-- Form Buttons -->
<div class="buttons" >
<input type="submit" name="submit" class="button" value="Submit" onclick="return validate(myform)" />
<input type="submit" name="cancel" class="button" value="Cancel" />
</div>
<!-- End Form Buttons -->
</form>
I tried your code in a jsfiddle, and it wasn't calling validate. Removing most of your javascript and leaving just a basic validate did call validate. So I think your javascript has syntax errors and the form is ignoring it before submitting. So:
Change the cancel button to type=button, so that it doesn't default to submitting the form when you mean to cancel the submission.
Open firebug, or at the very least the javascript console (in some browsers called the 'error console') and look at the errors you get.
Learning how to debug the javascript will help this time and in the future. Javascript can be completely discarded by the browser if there are syntax errors, in which case your form will just submit as though there was no javascript at all.
Don't see that as a suggestion to only submit via javascript, however, as that would prevent users with javascript switched off from being able to use your form. But that cancel-button-that-submits has to go.