I am trying to use a simple jquery/php newsletter script. The script works fine. As I enter name and email and hit the submit button, it saves data into a .txt file, and display a success message along with the form. Now, I would like to modify the script. I do not want the form to be seen as I hit the submit, instead it should show the success message only "Thank you." Being very novice to javascript, I have so far figured out that I need to "fadeOut" the form after clicking the submit button.
I think the code might be look like
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});
I have tried to integrate this code, but due to my limited JS experience I cannot do it successfully.
Here is my original jquery script
var error_1 = "Please enter your valid email address";
var error_2 = "Please enter your name";
var thankyou = "Thank you";
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function $Npro(field) {
var element = document.getElementById(field);
return element;
return false;
}
function emailvalidation(field, errorMessage) {
var goodEmail = field.value.match(/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/);
apos = field.value.indexOf("#");
dotpos = field.value.lastIndexOf(".");
lastpos = field.value.length - 1;
tldLen = lastpos - dotpos;
dmLen = dotpos - apos - 1;
var badEmail = (tldLen < 2 || dmLen < 2 || apos < 1);
if (!goodEmail || badEmail) {
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
field.focus();
field.select();
return false;
} else {
return true;
}
}
function emptyvalidation(entered, errorMessage) {
$Npro("Error").innerHTML = "";
with(entered) {
if (trim(value) == null || trim(value) == "") { /*alert(errorMessage);*/
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
return false;
} else {
return true;
}
} //with
} //emptyvalidation
function signup(thisform) {
with(thisform) {
if (emailvalidation(email, error_1) == false) {
email.focus();
return false;
};
if (emptyvalidation(name, error_2) == false) {
name.focus();
return false;
};
}
$("#submit, #myResponse").hide(); // Hide the buttom and the message
$("#loading").show(); // show the loading image.
params = $("#subform").serialize();
$.post("optIn.php", params, function(response) {
//alert(response); //may need to activate this line for debugging.
$("#loading").hide();
$("#myResponse").html(thankyou); //Writes the "Thank you" message that comes from optIn.php and styles it.
$('#myResponse').css({
display: 'inline',
color: 'green'
})
$("#submit").show();
})
return false;
}
Here is the html markup
<form onSubmit="return signup(this);return false;" method="post" name="subform" id="subform" action="
<?php echo optIn.php ?>">
<div>
<span style="FONT-FAMILY: Arial; FONT-SIZE: 12pt; font-weight:bold;">Subscribe to our newsletter</span>
</div>
<div style="margin-top:20px">
<div>
<label style="display: inline-block;width:135px">Email:</label>
<input type="text" id="email" name="email" value="">
</div>
<div>
<label style="display: inline-block;width:135px">Name:</label>
<input type="text" name="name" id="name" value="">
</div>
<div>
<div style="display:inline-block;width:135px;"> </div>
<input type="submit" id="submit" name="submit" value="Sign up">
</div>
<div style="width:100%">
<span id="Error" style="color:red;display:none;"></span>
</div>
<div id="myResponse" style="DISPLAY:none;"></div>
<div id="loading" style="display:none;">
<img src="wait.gif" alt="">
</div>
</div>
</form>
Here is my php code:
<?php
//ini_set('display_errors', 0);
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$email = trim(htmlspecialchars($_REQUEST["email"]));
$name = trim(htmlspecialchars($_REQUEST["name"]));
$pfileName = "mails.txt";
$MyFile = fopen($pfileName, "a");
$nline="\"".$email."\"" ."," ."\"".$name."\"" ."\r\n";
fwrite($MyFile, $nline);
fclose($MyFile);
die;
?>
Try providing a .delay() so that the fadeOut() function has finished before attempting to display the success message:
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").delay(500).fadeOut(280, function() {
$(this).after('<p id="success">Thank you</p>');
});
});
If I understand you correctly you want the user to submit the information via your html form. Then you want the form to go away after you hit the submit button.
From reading the JQuery method you have tried I found one mistake that is preventing your form from fading out. You were using the wrong id for your form in your JQuery code(it should be subform according to your html). Note that I removed your PHP code so that I could create an example in jsfiddle for you. My sample posts to google.com to prevent your from getting an error page displayed in the results sections.
jsfiddle: fade out form on submission
$("#submit").on("click", function(e) {
//changed from e.stopImmediatePropogation()
e.preventDefault();
//#subform is the actual id of your form, you were using signup
$("#subform").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});
Related
I have been searching for hours and trying other code samples find on here and other places but nothing seems to work.
I only want my form to go to the action url if the email field is neither empty or invalid. If not i want nothing to happen except show my error message. This is my current script i am using but when my unsubscribe button is clicked it seems to go to the action url no matter what.
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9] .
{2,4})+$/;
return regex.test(email);
}
function validateForm() {
if( !isEmail( document.getElementById('email_address').value ) ) {
var err = document.getElementById('error');
err.show();
$( "#submit" ).click(function( event ) {
event.preventDefault();
return false;
} else {
return true;
}
}
and the html looks like this
<p id="error">Please enter your email address</p>
<form id="myForm" method="post"
action="https://fe3e15707564057a7d1470.pub.s10.sfmc-
content.com/tfuryofct5y?
optc=%%=v(#optc)=%%&brand=%%=v(#brand)=%%&ceid=%%=v(#ceid)=%%"
onsubmit="return validateForm();">
<input type="text" placeholder="email address" name="email_address"
id="email_address" align="center"/>
<p style="text-align:center;overflow:hidden;float:right;padding-
right:8em;">
<input id="submit" type="submit" value="Unsubscribe" ></p>
</form>
Jquery is not my strong suit so they may be way off.
You are mixing javascript and jquery and causing the onclick to submit the form.
function validateForm() {
var err = $('#error');
if( !isEmail( document.getElementById('email_address').value ) ) {
err.show();
return false;
} else {
err.hide();
return true;
}
}
I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE
first of all I'd like to say I realise it's not a secure method.
This is only for training purpose.
The algorhitm should be:
click on a div with id="login-bg"
app displays the banner
provide the code
if the code's ok set cookie and fade out the banner
if the code's not ok the div shakes (still remaining on the screen)
if you don't want to provide the code press 'cancel' and fade out the banner
Set cookie function (it works fine):
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<script type="text/javascript">
function SetPwd(c_name,value,expiredays){
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+";path=/"+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
</script>
<?php } ?>
And here must be the problem with jQuery:
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy"/>
</form>
<h3>And enjoy free access!</h3>
<a id="cancel">Cancel</a>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
if( document.cookie.indexOf("is_logged") ===-1 ){
$('#video').click(function(){
$("#login-bg").fadeIn('slow');
});
$('#cancel').click(function(){
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
}
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
});
</script>
<?php } ?>
In my opinion the value '#code' id not passed to jQuery from the form.
But I may be wrong.
Do you have any ideas. Could you make it work?
Thanks for your help.
looks to be a problem here..
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
this will not equate the way you want it to:
if( value == test )
I would suggest changing it to,
if( value == pass )
also change
$("#submit").click(
to
$("#enjoy").click(
I've changed. However, the system still does not behave as it should. When I click 'submit' the banner just disappears ( doesn't matter if the code is ok or not ).
I think the value is not passed because when I do a simple test there's any alert:
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
alert(value);
if( value == pass ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
Yes, your click handler for the submit was not correct and at the password check you've missed the quotes 'test'. (As the others already answered.)
Below is the demo of your code and here at jsFiddle. It uses the jQuery cookie plugin for the cookies, but your PHP cookies will work too. I have just no backend for the demo.
Sorry, it's not working on SO because of insecure operation, probably the cookies are not allowed here. But at jsFiddle it is working.
Also don't remove the login div with $("#login-bg").remove(); because it will be removed from DOM and you can show it again to the user. It's better to only hide it.
// if(!isset($_COOKIE['is_logged']))
$(document).ready(function () {
if (!$.cookie('is_logged')) {
console.log('not logged in, show form');
//document.cookie.indexOf("is_logged") === -1) {
//$('#video').click(function () {
//$('#code').val(''); // clear input
$("#login-bg").fadeIn('slow');
//});
$('#cancel').click(function () {
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
} else {
$('#mainContent').fadeIn('slow');
}
$('#logout').click(function () {
console.log('hide clicked');
$('#code').val(''); // clear input
$('#mainContent').hide();
$("#login-bg").fadeIn('slow');
$.removeCookie('is_logged');
});
$("#check-form").on('click', 'input[type=submit]', function (evt) {
evt.preventDefault();
var value = $('#code').val();
var pass = 'test';
if (value == pass) { // 'test') {
//SetCookie('is_logged', 'is_logged', 365 * 10)
$.cookie('is_logged', 'true', {
expires: 7
});
$('#mainContent').fadeIn('slow');
$("#login-bg").hide(); // don't remove the login section
} else {
$('#login-bg').effect("shake");
}
});
});
#login-bg {
display: none;
}
#mainContent {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy" />
</form>
<h3>And enjoy free access!</h3>
<a id="cancel" href="#">Cancel</a>
</div>
</div>
<div id="mainContent">
<strong>Login succeeded!</strong> Shown after login!!
<a id="logout" href="#">Logout</a>
</div>
Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
I'm a javascript newbie and I'm attempting to combine two pieces of code which are working individually but not together:
Validate my form to check that the length, width and height are non-zero
If form is valid, submit form and display a css splash loading screen while the content loads
Here is my unsuccessful attempt:
<script type = "text/javascript">
function notEmpty(elem, helperMsg){
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show() {
if ((notEmpty(document.getElementById('length'), 'Please Enter a Length')==true) &&
(notEmpty(document.getElementById('height'), 'Please Enter a Height')==true) &&
(notEmpty(document.getElementById('weight'), 'Please Enter a Weight')==true)) {
document.getElementById("myDiv").style.display="block";
setTimeout("hide()", 10000); // 10 seconds
}
}
function hide() {
document.getElementById("myDiv").style.display="none";
}
</script>
My form will call show() on form submit. And myDiv is a css loading page element which appears while the page loads. Again, I apologize if my attempt is way off, I am very new to javascript, and would appreciate any advice to point me in the right direction.
In HTML form add onClick="validate(event)" to the submit button:
<form action="someAction">
<input type="text" id="length"/><br/>
<input type="text" id="height"/><br/>
<input type="text" id="weight"/><br/>
<input type="submit" onClick="validate(event)"/>
</form>
<div id="myDiv" style="display: none">Loading....</div>
then try this code:
function validate(e) {
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;//stop the form from submitting before validating
var arr = ['length', 'height', 'weight'],
valid = true,
helperMsg = ['please choose length value', 'please choose height value', 'please choose weight vale'];
for (var i in arr) {
var elm = document.getElementById(arr[i]);
if (elm.value.length == 0) {
alert(helperMsg[i]);
elm.focus();
valid = false;
break;//stop looping and move to the next step
}
}
if (valid) {
var div = document.getElementById('myDiv');
document.getElementsByTagName('form')[0].submit();//submit the first form, or you can change it to document.getElementBY('id') instead if you add an id to your form which would be better.
div.style.display = 'block';//show div
setTimeout(function () {
div.style.display = 'none';//hide div after 10 sec
}, 10000);
}
}
DEMO
The following is a working solution(may not be the best or ideal), that should work for you as well. Try attaching the function to the submit button. Make it type 'button' attach the 'show' to its click event and modify the 'show' method slightly as shown below. Hope this helps:
<html>
<head>
<script type = "text/javascript">
function notEmpty(elem, helperMsg){
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show() {
if ((notEmpty(document.getElementById('length'), 'Please Enter a Length')==true) &&
(notEmpty(document.getElementById('height'), 'Please Enter a Height')==true) &&
(notEmpty(document.getElementById('weight'), 'Please Enter a Weight')==true)) {
document.getElementById("myDiv").style.display="block";
setTimeout("hide()", 10000); // 10 seconds
document.getElementById("myform").submit();
}
}
function hide() {
document.getElementById("myDiv").style.display="none";
}
</script>
</head>
<body>
<form id="myform" action="someAction" onSubmit="show()">
<input type="text" id="length"/>
<input type="text" id="height"/>
<input type="text" id="weight"/>
<input type="button" value="submit" id="mySubmitBtn" onClick="show()"/>
</form>
<div id="myDiv"></div>
</body>
</html>