JavaScript Not Submitting Form - javascript

I've spent the last hour or so trawling through here and Google without success. I have a form that I want to submit via POST. The javascript runs and validates fine, it even 'submits' the form. But when it does, it just reloads the page. No POST headers are sent (confirmed using Firebug in Firefox). It's as though it simply reloads the page rather than submitting it.
This form is embedded in the addUser.php page.
<form action="addUser.php" method="post" name="NewUser">
<div data-role="field-contain">
<label label-for="EmpID" class="ui-hidden-accessible">Enter Employee ID</label>
<input name="EmpID" id="EmpID" placeholder="Employee ID" value="" autocomplete="off" title="Enter Employee ID" type="number" required autofocus>
<label label-for="UserName" class="ui-hidden-accessible">Enter username</label>
<input name="UserName" id="UserName" placeholder="Username" value="" autocomplete="off" title="Enter the new username" required>
<p>
<label label-for="NewPass1" class="ui-hidden-accessible">Enter Your Current Password</label>
<input name="NewPass1" id="NewPass1" placeholder="New Password" value="" type="password" autocomplete="off" title="Must be at least 8 characters, with numbers and upper and lower case letters." required>
</p>
<p>
<label label-for="NewPass2" class="ui-hidden-accessible">Enter Your Current Password</label>
<input name="NewPass2" id="NewPass2" placeholder="Verify Password" value="" type="password" autocomplete="off" title="Re-enter your chosen new password." required>
</p>
</div>
<button type="button" name="submitButton" value="submitButton" data-theme="d" data-inline="true" data-icon="check" data-iconpos="left" onclick="validateForm ()">
Add User
</button>
And here is the Javascript:
function validateForm()
{
var reason = "";
reason += validateEmpID();
reason += validateUserName();
reason += validateNewPassword();
if (reason != "") {
alert("There are some errors with the data you entered:\n" + reason);
return false;
} else {
document.NewUser.submit();
}
}
I have tried various different methods of calling submit, all with the same result. Any help greatly appreciated.
Thanks
Gareth

I think it should be
document.forms['NewUser'].submit();
or
document.forms.NewUser.submit();

I think somewhere you are missing adding return false that is the reason your browser is asking for reloading the form. And better way to submit is to use submit button instead of using simple button.

Why not use an AJAX post? Or better yet a jQuery AJAX POST?
$.post(url, data, datatype);
http://api.jquery.com/jQuery.post/

function validateForm(event) {
var reason = "";
reason += validateEmpID();
reason += validateUserName();
reason += validateNewPassword();
if (reason != "") {
alert("There are some errors with the data you entered:\n" + reason);
event.preventDefault();
}
}
document.getElementById('my_form').addEventListener('submit', validateForm, false);

Related

why is my validation in password not working when connected with html page?

I have created a javascript page and connected it with html page. In the Javascript, i have created validation of the password and if there is a password mismatch then it will alert that there is a mismatch.
function validation()
{
if(password==repassword){
console.log(" ");
}
else{
alert(" ");
}
}
Above code is the javascript code and below is the html code.
LogIn
<label for="username">First Name: </label>
<input class="firstname" type="text" id="firstname" placeholder="First name"><br>
<label for="username">Last Name: </label>
<input class="lastname" type="text" id="lastname" placeholder="Last name"><br>
<label for="email">Email id: </label>
<input class="email" type="email" id="email" placeholder="Email id"><br>
<label for="labeltext">Password: </label>
<input class="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<label for="labeltext">Re-Password: </label>
<input class="Re-Password" type="password" id="repassword" placeholder="Re-Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<button class="Submit" onclick="validation()">Submit</button>
<button class="reset">Reset</button>
</form>
Does anyone know what's wrong in my code? Thank you!
You must create a reference for each element in javascript:
const password = document.getElementById('password');
const repassword = document.getElementById('repassword');
Now your variables are not local and you can use them in your function:
function validation()
{
if(password.value==repassword.value){
console.log(" ");
}
else{
alert(" ");
}
}
I believe what you want to do is to check if the password matches the verify password value.
From your javascript codes, everything looks good but if it is not working, then there is a problem with your HTML elements IDs i.e password field id and verify password field id. Check if you are making a mistake in any of the code you are using to get the element values.
A little mistake like
var x = document.getElementById("txtpass").value;
Where as, in your HTML source, there is no such element with txtpass as id could cause your javascript codes to break.
I would advise you post the complete HTML and Javascript codes.
Better still, use your browser console to check for the runtime error that is depriving your code from running as expected.
Use name=password in your password and name=repassword in your repassword tag like
<input class="password" name="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>

`Required` attribute not working with <form> tag [duplicate]

This question already has answers here:
HTML5 required attribute not working
(2 answers)
Closed last month.
My required attribute doesn't specify that an input field must be filled out before submitting the form.
HTML:
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="psw" onfocus="this.value=''"
required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword" placeholder="Confirm Password" name="psw-confirm" onfocus="this.value=''"
required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="button" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
JavaScript:
function signUp() {
if (document.getElementById("password").value == document.getElementById("cfmpassword").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username = document.getElementById("username").value;
users.email = document.getElementById("email").value;
users.password = document.getElementById("password").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true);
postUser.setRequestHeader("Content-Type", "application/json");
postUser.send(JSON.stringify(users));
//go to the logged in page
window.location = "main.html";
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
As the required attribute does not work, users can continuously submit empty forms and those will be stored in my SQL database
I don't have a <button type="submit"> in the form as this prevents me from using windows.location.
I am new to programming, can someone please give some suggestions (with explanations) on what to do to fix this? Any help would be appreciated! Thanks a lot! (I am using vanilla JavaScript for this)
The required attribute does not work because your form is not submitted. You need to specify a button with a type="submit" or <input type="submit"> to submit your form.
I suggest you to move the signUp function inside the form tag like this with an onsubmit event:
<form onsubmit="signUp(event)">.
Then add this to you Javascript function:
function signUp(event) {
event.preventDefault();
... your old code
}
For me, I see a number of possible issues. I have tried to remove them with the following sample code. I am assuming that /users will return something useful for checking and alerting the member if there is an error with the accessing of /users or the processing of the data.
The use of the required attribute of <input> will do nothing obvious in your code as the <button> has an onclick=signUp() call which will triggered before the browser check. With your current code the form values (present or not) will still be sent to /users as there is no testing for those values.
You need to move the signUp() call to the <form> if you want the browser check to be run.
To test this, removing the onclick=signUp() in the <button> will show you a browser tip window saying the value is needed.
As you are insisting on using AJAX to post the form data, moving the check to the <form> submit is idea and personally, I would still be checking the values - just good practice.
The next issue is you are not waiting for the return of a success or fail response from /users. In fact, you are blindly redirecting to main.html. If there is an error, the user will never know. This is a very bad user experience.
This is corrected in the sample code by checking for a response with a call-back, checking that response value and then alerting the member or redirecting if there is no error.
var users = {};
function ajaxPost(url,postData,callFunc) {
var http = new XMLHttpRequest();
if(! http){
return false;
}
http.onreadystatechange=function(){
if((http.readyState == 4) && (http.status == 200)) {
if(callFunc){
callFunc(http.responseText);
}
}
}
http.open('POST',url,true);
http.send(postData);
}
function validResult(str) {
if (str == "valid") {
// go to the logged in page
window.location = "main.html";
} else {
console.log("invalid result, let the user know");
}
}
function signUp(e) {
if(e){e.stopPropagation();e.preventDefault();}
var d = document.getElementById("signupForm").querySelectorAll("input");
var i, max = d.length;
// Quick check for values only. No check for the format of the values.
// This is good practice as a browser may still ignore the `required`
// attribute.
for(i=0;i<max;i++) {
d[i].value = d[i].value.trim();
if (d[i].value) {
users[d[i].name] = d[i].value;
} else {
// An alert would be better for the user here.
console.log("Missing value for ["+ d[i].name +"]");
// Go no further if there is a missing value.
return;
}
}
// at this point, all values added to the users object.
console.log("users:["+ JSON.stringify(users) +"]");
// Send the data and wait for a return value from /users
// --- remove comment on the following line to post ----
//ajaxPost("/users",JSON.stringify(users),validResult);
}
window.onload = function(){
var c = document.getElementById("signupForm");
if (c) {
c.addEventListener("submit",signUp,false);
}
}
<form id="signupForm">
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<p>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<p>
<button id="submit" type="submit">Check and submit</button>
</form>
Basic of HTML5 validation. You have it on button click and that runs before the validation happens. This shows you that the onclick runs and the onsubmit does not. Use the correct event.
function loginSubmit () {
console.log('loginSubmit')
}
function loginClick () {
console.log('loginClick')
}
<form onsubmit="loginSubmit()">
<input name="foo" required />
<button onclick="loginClick()">click</button>
</form>
The way required attribute works is it determines whether the element its assigned to has a value length higher than a zero, if that statement is false (meaning the value length of zero) then upon submitting the form it focuses that element as its "required" to be fulfilled.
Here is an example with JavaScript and how checking input fields could work inside it.
const form = document.querySelector('form[action="signup.php"]'); // Form
const inputs = form.querySelectorAll('input'); // All input elements inside the form
const submit = form.querySelector('button[type="submit"]'); // Submit button inside the form
// Add onclick event to the form button
submit.addEventListener('click', function(event) {
event.preventDefault(); // This prevents the button from submitting the form the traditional way
submit_form(); // but instead our way
});
function submit_form()
{
// We iterate through the form input elements
for (var i = 0; i < inputs.length; i++)
{
// We check if the current element has
// the attribute required and if so
// we proceed with checks
if (inputs[i].hasAttribute('required') && inputs[i].value.length == 0)
{
inputs[i].focus(); // We focus on the required element
alert(inputs[i].placeholder+' is required!'); // Alert the user that the element is required
break; // Break from the loop
}
else
{
if (i == (inputs.length - 1)) form.submit(); // If the loop's i variable counter hits the same value as the
// input elements length then it means all fields are filled
}
}
}
form {
width:300px;
margin:auto
}
form button,
form input {
width:100%;
height:48px;
padding:0 15px;
font-size:18px;
box-sizing:border-box;
}
form input:focus {
background-color:#f2dfb7;
}
<form action="signup.php" method="POST">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<input type="email" name="email_repeat" placeholder="Email Address (Repeat)" required>
<input type="password" name="password" placeholder="Password" required>
<input type="text" name="phone" placeholder="Phone Number" required>
<input type="text" name="birthday" placeholder="Birthday (MM/DD/YYYY)" required>
<button type="submit">Sign Up</button>
</form>

How to make sure a form is valid before submitting using JQuery?

I'm trying to make a login page and have the following:
<div id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</div>
I made sure that the username and password fields are required. When the login is successful (for this sake, let's just say that both fields are not empty) a login disappears and another view appears. Anyway, I checked to see if the login button is pressed with JQuery:
$(function(){
$('#submit').on('click', function(){
$('#loginField').hide();
$('#differentView').show();});
The problem is that when the login button is clicked, the required attributes gets ignore and the next view is shown. How do I make sure that the required attributes are not ignored when the login button is clicked?
A crude way of doing it...
<div id="loginField">
<input id="username" type="text" name="user" class="required">
<input id="password" type="password" name="password" class="required">
<input id="submit" type="submit" name="submit" value="Login">
</div>
$('#submit').on('click', function(e){
e.preventDefault();
var isReady = true;
$('.required').each(function(){
if (this.value === '') {
isReady = false;
return;
};
});
if (isReady) {
// submit form
};
});
You can use this library: Parsley. It is a javascript form validation library and it is very easy to use and you can customize it for your own means. Good luck!
Instead of handling onclick on button, you can put input fields into the form...
<form action="post" method="post" id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</form>
... and in jQuery you can handle on submit action like this:
$(document).ready(function(){
$('#loginField').on('submit', function(event){
event.preventDefault();
var [username password] = $(this).serializeArray(),
username = username.value,
password = password.value;
/* some validations */
});
});
event.PreventDefault prevents browser from subbmiting so your page won't be refresh. serializeArray returns an array of objects (key-value) that's why you have to use .value
The required attributes are ignored because the input elements are not inside an html form element
To use the HTML5 input valuation attributes (required, minlength... etc)
The inputs should be grouped inside a form element, and you can listen for the form submit event, that is triggered by default when the user press enter (while focus is on a field inside the form) or clicks the submit button (input or button with type="submit") that is also wrapped inside the form
HTML
<form id="loginForm">
<input id="username" type="text" name="user" required />
<input id="password" type="password" name="password" required />
<input id="submit" type="submit" name="submit" value="Login" />
</form>
Javascript
$(function(){
$('#loginForm').on('submit', function (event) {
event.preventDefault(); // prevent default form submit page reload
console.log('I will enter this handler only on valid form')
$('#loginForm').hide();
$('#differentView').show();
})();
Here is a basic plunker with 2 examples https://plnkr.co/edit/I0vUMSeOlrjlYYu4VofU?p=preview
using the default html5 validation
using Parsley

Google spreadsheet website form jQuery script block the sending of

I have my form in html. I copied action, entry keys and hidden inputs from orginal Google Form.
<form id="Gform" role="form" action="https://docs.google.com/forms/d/MY-FORM-KEY/formResponse" method="POST" target="_self" onsubmit="">
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{4,40}$" name="entry.1028663680" value="" id="entry.1028663680" dir="auto" title="What is Your city" class="form-control" placeholder="City" required>
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{5,40}$" name="entry.1220908348" value="" id="entry.1220908348" dir="auto" title="Your complete name" class="form-control" placeholder="Your name" required>
<input type="tel" name="entry.623688995" value="" id="entry.623688995" dir="auto" title="" class="form-control" placeholder="phone" required>
<input type="email" name="entry.1564973803" value="" id="entry.1564973803" dir="auto" title="" class="form-control" placeholder="email" required>
<input type="hidden" name="entry.383122401" value="WEBSITE" id="entry.383122401" dir="auto" title="" class="form-control" placeholder="E-mail" required>
<input type="hidden" name="draftResponse" value="[,,"-9139933475238999509"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fbzx" value="-9139933475238999509">
<button type="submit" name="submit" id="sendData" class="btn btn-default">Submit</button>
</form>
I have te jQuery script, which display confirm:
<script type="text/javascript">
function sendContactForm(){
$("#Gform").fadeOut();
$("#form-container").append('<p class="confirmer">Thanks!<br>Your email was sent.</p>');
};
$('#Gform').submit(function () {
sendContactForm();
return false;
});
</script>
When i delete this script, form is sending, and save to google, but after click submit, I am redirecting to google "Thank You" page. I want to no redirect and display confirm just like in script. How to fix this problem ?
try to use AJAX to acomplish your task, when you will use asynchronous function, there won't be reloading page and you will send data behind the scene. In data object enter all input values, in done() and fail() functions define what to do when you recieve response. Good Luck:)
$('#formID').submit(function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/1PrgHQALlz0WrvwjhGpLrtIgD5aQ1x-8HrOubkxTLNKs/formResponse",
type: "POST",
data: {
'entry.111': $('#entry_111').val(),
'entry.222': $('#entry_222').val(),
// all data from form
}
}).done(function(data){
yourAction(data);
}).fail(function(data){
failAction(data);
});
});
Comment the return false in the code above:
$('#Gform').submit(function () {
sendContactForm();
//return false;
});
Or just delete this line.
What this is script is doing is: subscribing to the submit event and canceling it.
Do you want to do something else?

Javascript form validation not working - Script not being called?

I have a pretty straight-forward javascript form validation script written:
function validateForm(){
var x=document.forms["contactForm"]["firstname"].value;
if (x==null || x==""){
return false;
}
var y=document.forms["contactForm"]["lastname"].value;
if (y==null || y==""){
return false;
}
var z=document.forms["contactForm"]["emailaddress"].value;
var atpos=z.indexOf("#");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length){
return false;
}
var msg_area = document.getElementById("message");
msg_area.innerHTML = "";
if (document.getElementById("message").value.length < 20) {
return false;
}
else document.getElementById("contactForm").submit();
}
It's supposed to be validating this form:
<form name="contactForm" onsubmit="return validateForm()" action="./thankyou.html" method="post">
<label for="firstName">First Name <sup>*</sup></label>
<input name ="firstname" id="firstName" type="text" placeholder="First Name" required />
<label for="lastName">Last Name <sup>*</sup></label>
<input name ="lastname" id="lastName" type="text" name="lastName" placeholder="Last Name" required />
<label for="emailaddress">Email address <sup>*</sup></label>
<input name="emailaddress" id="emailAddress" type="email" placeholder="something#example.com" required />
<label for="message">Message<sup>*</sup></label>
<textarea id="message" placeholder="Remember, be nice!" required></textarea>
<input type="submit" name="submit" value="Email Me!" class="emailsub" />
<p class="small"><sup>*</sup> denotes a required field.</p>
</form>
When it's submitted, it doesn't seem to actually call the javascript at all. The only thing that it looks for is that it meets the "required" part of the html. I'm pretty new to javascript so it's probably glaringly obvious where the problem is, but I just can't locate it myself.
Any help is much appreciated!
p.s. this is for a local website at the moment so the action="" goes to another html instead of a page to process the message. Is this possibly the problem here?
The html5 "required" attribute tells the browser to validate before proceeding, read more here. This means that it's stopping the event before the javascript function is even called (on supported browsers) unless it passes the basic validation (required fields and email).
If you want the javascript to execute and perform your own validation, you'll need to remove the "required" attribute. You may also try more complex html form validation. Here is a good article on the subject.

Categories

Resources