html5 form not working properly - javascript

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

Related

Form Validation not responding correctly

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.

Contact Form Redirecting Prevent Default Not Working

I've tried this many different ways... don't know why this is redirecting still. I suppose in the past I've always used a button instead of a submit input and as such I never ran into this issue. However, I think it's time to get to the bottom of this!
HTML FORM
<form class="col-xs-12" action="mail.php" method="POST" >
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<input type="submit" value="Send" onclick="formSubmit(e)">
</form>
JAVASCRIPT CODE
function formSubmit(e) {
e.preventDefault();
return false;
console.log("Ajax Init");
var form = e.target,
data = new FormData(),
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
break;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0){
xhr.send(data);
} else {
break;
}
xhr.onloadend = function () {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
};
It seems a better option is to use onsubmit attribute.
function formSubmit(form) {
console.log("Ajax Init");
var data = new FormData(form), // simpler
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
//data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
// something went wrong, prevent form from submitting
return false;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0) {
xhr.send(data);
} else {
// something went wrong, prevent form from submitting
return false;
}
xhr.onloadend = function() {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
// everything went ok, submit form
return true;
};
<!-- note the use of return -->
<form class="col-xs-12" action="mail.php" method="POST" onsubmit="return formSubmit(this)">
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<!-- upon clicking on the submit button, it will trigger the form's onsubmit handler -->
<input type="submit" value="Send">
</form>
i suggest to use jquery inside of core javascript becuase in javascript it to mush code want to write , i write for you in jquery
step 1: : give id to form tag id="myForm"
step 2: : write script like this
<script>
$('#myForm').submit(function(e){
e.preventDefualt();
data = $(this)..serialize();
});
</script>

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Simple JavaScript validation not working?

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

Validating form after error has been shown

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;
}

Categories

Resources