I'm new to HTML and JS and I'm trying to setup a "Contact" page using GitHub Pages. I am using formspree.io to submit the forms and e-mail to the app mail account.
Here is the deal: I'm trying to setup a simple validation just to verify if the form fields aren't empty (there is no need for a server-side validation), but the "onSubmit" response seems to be bypassed every single time.
Here is my contact.html file:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Helvetica;}
* {box-sizing: border-box;}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #b00faa;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 15px;
}
input[type=submit]:hover {
background-color: #780774;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
</head>
<body>
<h3>Formulário de Contato</h3>
<div class="container">
<form action="https://formspree.io/myEmailHere#mail.com" method="post" onsubmit="return validate();">
<label for="fname">Nome Completo</label>
<input type="text" id="fname" name="fname" placeholder="Seu nome completo...">
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="Seu e-mail...">
<label for="subject">Mensagem</label>
<textarea id="subject" name="subject" placeholder="Digite algo..." style="height:200px"></textarea>
<input type="submit" value="Enviar">
</form>
</div>
<p id="error_catch"></p>
<script>
function validate() {
var at = document.getElementById("email").value.indexOf("#");
var message = document.getElementById("subject").value;
var fname = document.getElementById("fname").value;
if (fname.length < 1) {
alert("Digite seu nome...");
return false;
}
if (at === -1) {
alert("E-mail inválido!");
return false;
}
if (message.length < 1) {
alert("Digite uma mensagem");
return false;
}
return true;
}
</script>
</body>
</html>
If I open the file locally on Google Chrome, it works just fine, the alerts show up and the form is not submitted until all fields have been filled.
When I open it on my GHPages, however, it bypasses the validate function and proceeds to Formspree captcha page.
A little bit more context (not sure if it influences)...
This file is being included on my index.html file using a JS function.
My index consists of 2 tabs that load a different HTML when clicked.
Here is the GitHub repo for more information: TellMeApp/support.
What I have already tried:
Correcting the Javascript function: I am aware that if an error is raised on the function, the submission follows on without validation.
Creating an additional function to submit the form via JS: works the same locally, not online...
Looking for solutions on Github Pages help: did not found anything related to this subject.
Any thoughts on what could be wrong here?
I thank you in advance!
Instead of using the onsubmit attribute, you can use the required attribute for the inputs like so:
<label for="fname">Nome Completo</label>
<input type="text" id="fname" name="fname" placeholder="Seu nome completo..." required>
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="Seu e-mail..." required>
<label for="subject">Mensagem</label>
<textarea id="subject" name="subject" placeholder="Digite algo..." style="height:200px" required></textarea>
If you are interested in reading more about the required attribute, you can find it here: HTML required Attribute - W3Schools.com
Related
I'm trying to change my "Submit" button style when a user clicks on it upon submitting the form.
The action attribute calls PHP file, but the actual data doesn't display until I remove onSubmit attribute from my form. Then I can't use sendBtn() function to change the style of the button.
Pseudo-class option is not good, because it would change the style even if the form is empty.
Any ideas?
PS. I'm on local server with MAMP and using Dreamweaver for editing.
<form class="customform" method="post" action="emailOnServer.php" method="post" onSubmit="return sendBtn();" autocomplete="on" >
<div class="s-12" onClick="formFocus()"><input id="imie" name="imie1" placeholder="Twoje imię" type="text" required </input></div>
<div class="s-12" onClick="formFocus()"><input id="email" name="email1" placeholder="Twój e-mail" type="email" required </input></div>
<div class="s-12" onClick="formFocus()"><textarea placeholder="Wiadomość" id="pole" rows="5" style="resize:none;" required></textarea </input></div>
<div class="custom2" style="width: 34%; float: right;" ><input id="se" type="submit" value="Wyślij" style="background-color:#92c500; color: white; border-color:#6C0;" ></input> </div>
<div class="custom1" style="width: 65%;" ><button id="resetButton" onclick="cleanBtn()" type="reset" style="background-color: #808080; color: white; border-color:#066; border-radius:2px;">Wyczyść </button></div>
<img id="tick123" src="img2/green-tick-icon-0.png" style="display: none; float:right; position:absolute; right:1%; top:86%; padding:0; margin:0; width: 28px; height: 28px;"/>
<img id="tick1234" src="img2/green-tick-icon-0.png" style="display: none; position:absolute; left:58%; top:86%; padding:0; margin:0; width: 28px; height: 28px;"/>
</form>
<!-- more code to change form style on focus -->
function sendBtn() {
if ( document.getElementById('email').value.indexOf("#")> 0 &&
document.getElementById('email').value.indexOf(".")> 2 &&
document.getElementById('imie').value != 0 &&
document.getElementById('email').value != 0 &&
document.getElementById('pole').value != 0){
document.getElementById('se').style.backgroundColor = "#00283A";
document.getElementById("tick123").style.display="block";
document.getElementById('se').value="Wysłano";
document.getElementById('email').disabled=true;
document.getElementById('imie').disabled=true;
document.getElementById('pole').disabled=true;
return true;}}
It's from a free template and I know I should've used css stylesheets to make it more readable
This is emailOnServer.php file:
<body>
Hello User
<?php $name = $_POST['imie1'];
echo $name; ?>
</body>
First, your HTML have some errors, e.g.:
<input id="imie" .... type="text" required </input>
// look here ^
// the tag is not closed correctly
should be
<input id="imie" name="imie1" placeholder="Twoje imię" type="text" required />
Anyway, if you need to remove the onsubmit attribute, you can do something like this
<form name="myform" ...>
...
</form>
then, the js
var form = document.forms.myform;
form.onsubmit = function(){
// do stuff
document.getElementById('se').style.backgroundColor = "#00283A";
// ...
}
This jsfiddle has an example code for your requirements. The form elements was simplified.
I have a form that sends an email. I send the data to AJAX and then to a php file. When the data successfully sends, I have a success function in my ajax. If the data sent successfully, I am wanting the form to display: none; (which I have accomplished) and for a new class to appear. I know that can be done with the addClass() method. However, I do not understand how I can accomplish this. The reason being is I created a simple div with a success message, so upon page load I am hiding that div. So, my thoughts were to remove the class of email-success because I have it set to display: none; and then to add the class of its child div email-success-container. This is not working.
Does anyone know how I can accomplish this?
<div class="white-green">
<!-- The success div when the email is successfully sent .. I want this to show after email sends-->
<div class="email-success">
<div class="email-success-container">
<div id="email-success-title">THANK YOU FOR CONTACTING OUR AGENCY!</div>
<div id="email-success-description">Your submission has been received and one of our team members will contact you shortly.</div>
</div>
</div>
<div class="project-container">
<div class="project-input-container">
<!-- Form for email.... it shows on page load-->
<form action="" autocomplete="on" method="POST" id="project-information-form">
<input type="text" class="input-borderless" id="project-name" placeholder="Your Name">
<input type="text" class="input-borderless" id="title-roll" placeholder="Title/Role">
<input type="email" class="input-borderless" id="project-email" placeholder="Email Address">
<input type="text" class="input-borderless" id="project-number" placeholder="Phone Number">
<input type="text" class="input-borderless" id="project-company" placeholder="Company/URL">
</div>
<div class="project-input-container2">
<textarea rows="3" class="input-borderless" id="project-description" placeholder="Describe the project"></textarea>
<input type="text" class="input-borderless" id="project-source" placeholder="How did you hear about us?">
<input type="text" class="input-borderless" id="project-socialMedia" placeholder="Which of our social media influenced you the most?">
<input type="text" class="input-borderless" id="project-humanTest" placeholder="Human Test: What day comess after Thursday?">
</div>
<input type="submit" id="submit-project" value="Send Project Inquiry">
</form>
</div>
My ajax success:
success: function (data) {
//console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to send email!");
alert(data);
} else {
$(".project-container").addClass("removeClass");
$(".white-green").addClass("email-success-container");
$(".white-green").removeClass("email-success");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Email Successfully sent!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
CSS for the div I am trying to get to show after the email sends:
.removeClass {
display: none;
}
.email-success {
display: none;
}
.email-success-container {
margin-left: 9%;
margin-top: 250px;
}
#email-success-title {
color: #ba5a45;
font-size: 3em;
}
#email-success-description {
color: #ba5a45;
font-size: 2em;
}
Does anyone know what I can do to accomplish this?
You can override the display: none; CSS using .show() and .hide().
$(".email-success").show();
This uses inline style attributes, which takes precedence over stylesheets.
You could use $(".classname").css("property","value"); for example: $(".email-success").css("display","block");
It's more general solution since with this you can change any property u want, not just display
I'm trying to simply show a loading gif once the form is submitted. My code is not working correctly for the loading gif to show. You'll see my image for the gif is set to visibility: hidden.
<script src="js/jquery-1.11.1.min.js"></script>
<div class="" style="width: 480px; margin: 0 auto; margin-top: 20px;" id="form_wrapper">
<img src="img/loader.gif" id="gif" style="display: block; margin: 0 auto; width: 100px; visibility: hidden;">
<div class="fade" id="form">
<form action="process_login.php" method="POST" name="simplelogin" id="login_form"><br />
<label for="username"> Username:</label>
<input type="username" name="username" id="username" size="30" required><br><br>
<label for="password"> Password:</label>
<input type="password" name="password" id="password" size="30" required><br><br>
<input class="load_button" type="submit" name="submit" id="submit" value="Submit" placeholder="Submit">
</form>
</div>
</div>
<div class="fifty"></div>
<script type="text/javascript">
$('.load_button').submit(function() {
$('#gif').show();
return true;
});
</script>
The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:
$('#login_form').submit(function() {
$('#gif').css('visibility', 'visible');
});
Also note that return true; is redundant in your logic, so it can be removed.
Button inputs don't have a submit event. Try attaching the event handler to the form instead:
<script type="text/javascript">
$('#login_form').submit(function() {
$('#gif').show();
return true;
});
</script>
Better and clean example using JS only
Reference: TheDeveloperBlog.com
Step 1 - Create your java script and place it in your HTML page.
<script type="text/javascript">
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'loading_bar.GIF';
div.innerHTML = "Loading...<br />";
div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
div.appendChild(img);
document.body.appendChild(div);
return true;
// These 2 lines cancel form submission, so only use if needed.
//window.event.cancelBubble = true;
//e.stopPropagation();
}
</script>
in your form call the java script function on submit event.
<form runat="server" onsubmit="ShowLoading()">
</form>
Soon after you submit the form, it will show you the loading image.
What about an onclick function:
<form id="form">
<input type="text" name="firstInput">
<button type="button" name="namebutton"
onClick="$('#gif').css('visibility', 'visible');
$('#form').submit();">
</form>
Of course you can put this in a function and then trigger it with an onClick
I'm using JQuery Validation on my form, and I'm trying to get the input elements to show a red border if the input is invalid, and also show the error message underneath the appropriate input element.
My HTML code is basically this:
<div id="formContainer">
<form id="mainForm" action="action.php" method="post">
<input class="formTextBox" type="url" name="website" placeholder="website" required />
<input class="formTextBox" type="email" name="email" placeholder="e-mail" required />
<button type="submit" class="buttonForm" id="submitBtn"> <span id="buttonContent">Snapshot my site</span> </button>
</form>
</div>
I've tried adding specific DIVs after the form (still in #formContainer), that will get populated with the error using the errorPlacement option. Inside the function I check the element's name attribute, and append the error to its corresponding div... but when I continue typing, or clicking between inputs, the error message keeps repeating and repeating and no error ever gets cleared (I see the same error message many times, one underneath the other).
I've tried putting each input element inside its own div (with a fixed width), and set the errorElement to DIV, so when JQuery Validation creates that new div and appends it next to the input element, it will get pushed underneath... but that caused some design issues, and I'd prefer the 2 error containers to be in the #formContainer div (and it seems a little bit wonky to do it that way).
Also, what do I do if need to style both the error on the input element, and the error message DIVs?
Here's a little illustration of what I had in mind:
Thanks!
Try
<div id="formContainer">
<form id="mainForm" action="action.php" method="post" novalidate>
<div class="input-control">
<input class="formTextBox" type="url" name="website" placeholder="website" required />
</div>
<div class="input-control">
<input class="formTextBox" type="email" name="email" placeholder="e-mail" required />
</div>
<button type="submit" class="buttonForm" id="submitBtn"> <span id="buttonContent">Submit</span>
</button>
</form>
</div>
then
#formContainer {
vertical-align: top;
}
.input-control {
display: inline-block;
vertical-align: top;
}
div.error {
display: block;
background-color: red;
color: white;
}
input.error {
border: 1px solid red;
}
.formTextBox {
width: 210px;
background-color: white;
color: black;
}
and
jQuery(function ($) {
var validator = $('#mainForm').validate({
rules: {},
messages: {},
errorElement: "div"
});
});
Demo: Fiddle
<html>
<head>
<title> Form Validation </title>
<style type="text/css">
fieldset { width: 280px; padding: 6px; }
label { float: left; width: 100px; font: 12px Arial; padding: 5px; }
input { margin-bottom: 5px; }
</style>
</head>
<body>
<form id="inputForm" onsubmit="return validateForm();" action="#">
<fieldset>
<label>First Name:</label><input type="text" name="first_name" /><br />
<label>Surname:</label><input type="text" name="surname" /><br />
<label>Postcode:</label><input type="text" name="postcode" /><br />
<label>Email:</label><input type="text" name="email" /><br />
<input type="submit" name="submit" value="Send form" />
<input type="reset" name="reset" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
function validateForm() {
var form = document.forms['inputForm'];
var formats = {
First_name: /^[a-z]+[\-`\s]?[a-z]+$/i,
Surname: /^[a-z]+[\-`\S]?[a-z]+$/i,
Postcode: /^\d{4}$/,
Email:/^w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/
};
var elCount = form.elements.length;
for(var i = 0; i <elCount; i++) {
var field = form.elements[i];
if(field.type == 'text') {
if(!formats[field.name].test(field.value)) {
alert('Invalid '+field.name.replace('_', ' '));
field.focus();
return false;
}
}
}
}
</script>
</body>
</html>
Hey guys trying to figure out why the code is giving me a error:underfinded formats[fields.Name] but its has been defined. Its just a simple form so I am not sure what I am doing wrong. Sorry for the basic question but I have been looking over it multiple time and can't see it. Cheers again.
Assuming the error you are talking about is on this line:
if(!formats[field.Name].test(field.value)) {
I'd suggest using a lowercase "n" in the "name" property:
if(!formats[field.name].test(field.value)) {
JavaScript is case sensitive.
UPDATE: In addition to what I've already mentioned, but still regarding case sensitivity, your formats object has property names with mixed case, e.g., First_name, but the corresponding input elements have a name attribute in lowercase, e.g., name="first_name", so when you retrieve an element's name and try to use it to look up the property in formats it will return undefined. You need to make those match case.
Fix those errors and it works: http://jsfiddle.net/M4Nzr/