Reset My form after submission - javascript

After my form is submitted, I'd like to reset my form to display the original blank values. Here's the code:
PHP Form
<form action="index.php" method="post" id="contact_form" >
<div id="topic_error" class="error"><img src="images/error.png" /> What category should this be filed in?</div>
<div>
<select name="topic" id="topic">
<option value="">Please select a topic...</option>
<option value=" Computer Repair ">Computer Repair</option>
<option value=" Website Design ">Website Design</option>
<option value=" Say Hi ">Just Want to Say Hi</option>
</select>
</div>
<h4>NAME:</h4><div id="name_error" class="error"><img src="iamges/error.png" /> Please enter your name</div>
<div><input class="contact_name" type="text" name="name" id="name" placeholder="Enter Name" /></div>
<H4>EMAIL:</H4><div id="email_error" class="error"><img src="images/error.png" /> Please enter your email</div>
<div><input class="contact_email" type="text" name="email" id="email" placeholder="you#mail.com" /></div>
<h4>SUBJECT:</h4><div id="subject_error" class="error"><img src="images/error.png" /> Please enter a subject</div>
<div><input class="contact_subject" type="text" name="subject" id="subject" placeholder="How did you become so awesome?" /></div>
<h4>MESSAGE:</h4><div id="message_error" class="error"><img src="images/error.png" /> Please give us a few more details</div>
<div><textarea class="contact_message" name="message" id="message" placeholder="Give us some details"></textarea></div>
<div id="mail_success" class="success"><img src="images/success.png" /> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="images/error.png" /> Sorry, we don't know what happened. Please try again later.</div>
<div id="cf_submit_p">
<input class="submit" type="submit" id="send_message" value="">
</div>
</form>
The contact.js file
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var topic = $('#topic').val();
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(topic.length == 0){
var error = true;
$('#topic_error').fadeIn(500);
} else {
$('#topic_error').fadeOut(500);
}
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
} else {
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
} else {
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
} else {
$('#message_error').fadeOut(500);
} if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#cf_submit_p').remove();
$('#mail_success').fadeIn(500);
} else {
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
});
I don't think the send_email.php file is needed, but I can put that up here if need be. I would assume (I know what happens when you assume) that this can be done with some sort of trigger in the javascript. I did try to add the line form.trigger('reset'); after the $('#mail_success').fadeIn(500); line but that did not work

It would be $("#contact_form").trigger("reset"), and $("#contact_form")[0].reset() should also work.

$('#contact_form').trigger('reset') should work.

Related

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

JQuery HTML form validation still triggers email with blank entries

I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}

How to do for loop for display all errors at once in JavaScript?

I am currently working on JavaScript form validation. For individual it is applying all errors but my task is to loop all element at once and display error at once. Is there any solution?
<form action="" id="register" onsubmit="return validation()">
Name<input type="text" id="name">
<p id="error"></p>
Email<input type="text" id="email">
<p id="error"></p>
Password<input type="text" id="password">
<p id="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function validation() {
if (document.getElementById('name').value=="") {
document.getElementById("error").innerHTML="Please fill your name";
}
and so.. on..
}
</script>
Can anyone help me how to for loop all errors to display at once when user click submit buttton?
First of all, create an error box. This can be done using a simply div.
<div id="error-box" style="color: red"></div>
Second, you don't need to chain infinite if statements. You can use the fantastic and wonderful for loop!
function validation() {
var inputs = document.forms['myForm'].getElementsByTagName('input').length;
for (i = 0; i <= inputs; i++) {
if (document.forms['myForm'][i].value == "") {
document.getElementById("error-box").innerHTML="Please fill " + document.forms['myForm'][i].name;
}
}
}
This will create an array of inputs and read one by one. If any field is empty, it will return an error into your error box. If not, execution continues.
Or you can use jQuery and Validation plugin. Check here for more info. A simple jQuery form validation script
Happy coding!
First the id should be unique in same document so you have to replace duplicate ones by classes, e.g :
Name<input type="text" id="name">
<p class="error"></p>
Email<input type="text" id="email">
<p class="error"></p>
Password<input type="text" id="password">
<p class="error"></p>
Then just show the error message of the input in the related .error paragraph :
function validation() {
if ($('#name').val()==="") {
$('#name').next(".error").html("Please fill your name");
}
}
Hope this helps.
$('#register').on('submit', function(){
var submit = true;
if ($('#country').val()==='-1'){
$('#country').next(".error").html("Please fill your country");
submit = false;
}else
$('#country').next(".error").html("");
if ($('#name').val()===""){
$('#name').next(".error").html("Please fill your name");
submit = false;
}else
$('#name').next(".error").html("");
if ($('#email').val()===""){
$('#email').next(".error").html("Please fill your email");
submit = false;
}else
$('#email').next(".error").html("");
if ($('#password').val()===""){
$('#password').next(".error").html("Please fill your password");
submit = false;
}else
$('#password').next(".error").html("");
if ($('[name="check"]:checked').length===0){
$('[name="check"]:last').next(".error").html("Please check one at least");
submit = false;
}else
$('[name="check"]').next(".error").html("");
return submit;
})
.error{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="register" id="register">
Country
<select name="country" id="country">
<option value="-1">Select country please</option>
<option value="usa">USA</option>
<option value="austriala">Austriala</option>
<option value="india">India</option>
</select>
<p class="error"></p>
Name <input type="text" id="name">
<p class="error"></p>
Email <input type="text" id="email">
<p class="error"></p>
Password <input type="text" id="password">
<p class="error"></p>
Checkboxes
<br>
<input type="checkbox" name="check" value="check_1">check 1
<br>
<input type="checkbox" name="check" value="check_2">check 2
<br>
<input type="checkbox" name="check" value="check_3">check 3
<p class="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
Hmm. How about a native way? :)
function select( cssSelector ){ return document.querySleectorAll( cssSelector ) };
var inputs = select( '#register input' ); // selects array of all child inputs
//setup all validations within an object
var validations = {
name: function( nameText ){
//shorthand if-statements, expand if you need to
return ( nameText === "" ) ? "error, cannot be empty" : "ok";
},
password: function( passText ){
return ( passText.length < 8 )? "too short" : "ok";
}
};
//iterate over all inputs
for( var elem in inputs ){
if( validations[ inputs[ elem ].id ] ){ // if validation rule exists..
console.log( "input nr " + elem + "tested\n" +
"id = " + inputs[ elem ].id + "\n" +
"outcome: " + validations[ inputs[ elem ] ] );
}
}
I have not tested this so there might be typos

Ajax-PhP communication

I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>
Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.

What condition for my javascript do I need? Its a script that pops up a dialogue box with form validation remarks for fields left blank

I have a form and a script that makes a dialogue box pop up if a field is left blank. The thing is, is that it only works if both fields are left blank. I'm trying to figure out how to get it to work correctly when and if one of the fields is left blank.
SCRIPT
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
if(sendMsg.mile.value=='' || isNaN(sendMsg.mile.value))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(sendMsg.location.value=='' || isNaN(sendMsg.location.value))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Form
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
Fixed it now, added input pattern to make sure only digits aswell as req'd on tags.Again I can't format the code in an answer so I'm adding another as I'd be here all night
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n in Numbers only\n";
}
if(location=='')
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="text" pattern="[0-9]+" class="form-control" data-validation-required-message="Please enter your Google Mileage" required id="mile" name="mile"/>
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" required placeholder="BUSINESS NAME" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
change:
isNaN(sendMsg.locaition.value)
to:
isNaN(sendMsg.location.value)
Try this
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="number" min="0" max="2000" class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value();
var location=document.getElementById("loc").value();
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(location=='' || isNaN(location))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>

Categories