Single click to submit form - javascript

I'm having an issue when trying to submit my form. I have made a workaround so that the input gets sent to parse.com by using a hidden button which is visible until all fields are filled in, then this button is hidden and the real submit button is enabled. The problem is that I want to be able to submit the form directly by clicking the submit button without having to click the button twice. I have the following HTML:
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
Javascript:
<script type="text/javascript">
function getFullemail() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
e.preventDefault();
}else {
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
}
}
</script>
<script>
function functions() {
sendTheMail();
}
</script>
Parse.com script
$(document).ready(function() {
var parseAPPID = "bla";
var parseJSID = "bla";
Parse.initialize(parseAPPID, parseJSID);
var VcardObject = Parse.Object.extend("VcardObject");
$("#vcardForm").on("submit", function(e) {
e.preventDefault();
console.log("Handling the submit");
//add error handling here
//gather the form data
var data = {};
data.name = $("#name").val();
data.vorname = $("#vorname").val();
data.fullemail = $("#fullemail").val();
data.telefon = $("#telefon").val();
data.firma = $("#firma").val();
var vcard = new VcardObject();
vcard.save(data, {
success:function() {
openPage('danke');
console.log("Success");
},
error:function(e) {
console.dir(e);
}
});
});
});

If i understand you correctly, you'd like to click button after form is filed and if all fields are valid the form should be send. If so you need to do following changes:
1) remove from html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
2) change your validateForm - replace this lines
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
with
functions()

It will spare your from using two buttons.When submit button is clicked check if all the fields are filled in or not.Use && operator instead of || operator.Because you want all the fields to be filled
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' )
If all fields are filled it will alert a message which will tell you that your form is submitted.Otherwise it will alert you to fill all the fields
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' ) {
alert('form is sumbitted.');
e.preventDefault();
}else {
alert('fill all fields !!');
}
}
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="validateForm()" value=" submit " >

modify validateForm
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
return false
}
return true
}
and replace
console.log("Handling the submit");
//add error handling here
//gather the form data
with
if(!validateForm()) return
sendTheMail(...al your params here)
and the last step replace in your html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
with
<input type="submit" id="submitBtn" value=" ">

Related

HTML form automatically tries to validate and doesn't wait for the submit button to be clicked

I have this HTML form:
<form onclick="return validateForm();">
<h1 style="color:whitesmoke;">Register</h1>
<h2>Please enter your details:</h2>
<br />
<input type="email" name="email" placeholder="example#email.com" />
<input type="password" name="password" placeholder="Password" />
<br />
<input type="text" name="FirstName" placeholder="First name" />
<input type="text" name="LastName" placeholder="Last name" />
<br />
<div style="position:relative; top:10px;">
<label>Birth Date: <input type="date" id="birthday" name="DateOfBirth"></label>
</div>
<br />
<input type="number" placeholder="Age" min="10" max="120" name="age" style="width:15%;" />
<br />
<label style="position:relative; right:20px; top: 10px;">
Gender: <input id="setD_male" type="radio" name="gender" checked>
<label for="setD_male">Male</label>
<input id="setD_female" type="radio" name="gender">
<label for="setD_female">Female</label>
</label>
<br />
<div style="position:relative; top:10px;">
<input id="checkmark" type="checkbox" /><label> I agree to the terms and regulations.</label>
</div>
</div>
<br />
<input type="hidden" name="error" value="">
<button type="submit" id="Register" name="Register" class="submit-button">Register</button>
</form>
and this JavaScript:
var checkbox = document.getElementById("checkmark");
var button = document.getElementById("Register");
button.disabled = true;
checkbox.addEventListener("change", function () {
button.disabled = !checkbox.checked;
});
function validateForm() {
var error;
var email = document.getElementsByName("email")[0].value;
if (!email.endsWith(".com")) {
alert("Email has to end with '.com'");
return false;
}
var password = document.getElementsByName("password")[0].value;
var FirstName = document.getElementsByName("FirstName")[0].value;
var LastName = document.getElementsByName("LastName")[0].value;
var DateOfBirth = document.getElementsByName("DateOfBirth")[0].value;
var age = document.getElementsByName("age")[0].value;
var gender = document.getElementsByName("gender")[0].value;
if (
email === "" ||
password === "" ||
FirstName === "" ||
LastName === "" ||
DateOfBirth === "" ||
age === "" ||
gender === "" ||
email === null ||
password === null ||
FirstName === null ||
LastName === null ||
DateOfBirth === null ||
age === null ||
gender === null
) {
error = "nullRegistration";
window.location.href = "systemMessagesjsp.jsp?error=" + error;
return false;
}
if (
!Register(emailAddress, password, firstName, lastName, DOB, age, gender)
) {
error = "CantCreateUser";
window.location.href = "systemMessagesjsp.jsp?error=" + error;
return false;
} else {
alert("successfully signed in");
return true;
}
}
When I debug it, I can see that upon entering this page on my browser, the function "validateForm()" is being called, and also called again when I click the submit button. Why is it being called upon entering ?
I tried debugging it and I could see that upon entering the page, it jumps straight into validateForm and does all of the code inside of it, where instead, it should only perform the code inside of it if the user hits the submit button at the bottom of the page. I guess it registers the button from the previous stage as the submit button for some reason.
Use the submit event instead of the click event on the form.
<form onsubmit="return validateForm();">

html javascript form no longer working since adding new input field

I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

How to submit a form from script

I have a simple form:
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="button" value="SUBMIT" id="submit" onclick="empty()"/>
</form>
and an empty() function for checking if all inputs are there:
function empty(){
var x; var y; var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false;
}else{
document.form.submit(); /*this doesn't work*/
}
}
But I can't seem to get the form to submit...
The problem is with the button type. Try this:
<script>
function empty() {
var x;
var y;
var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false; // the only reason this worked previously is that the input type was wrong so the form didn't submit
} else {
return true; // return true instead of trying to submit the form with js
}
}
</script>
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="submit" value="SUBMIT" id="submit" onclick="return empty();" />
<!-- change the button type to submit and return the value from the empty function (false will prevent the default action of the button - stop the form submitting, true will allow the form to submit) -->
</form>
<div id="errors"></div>
Noticed this doesn't work as a snippet so this is it working in a fiddle
You need to define name of the form.After define this form can be submit using javascript.
To check example you can follow this example-
<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
Search
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>

innerHTML not affecting div

I have a problem with innerHTML
I'm trying to replace all child elements of a div (wipe it out) and replace with a text. Just to give you idea, this is a registration form, after clicking submit, it should clear the form and output some text. It looks like it doesn't take any affect on the div that I am targeting
here is the function
function signup() {
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if (u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "") {
status.innerHTML = "Fill out all of the form data";
} else if (p1 != p2) {
status.innerHTML = "Your password fields do not match";
} else if (_("terms").style.display == "none") {
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText.trim() != "signup_success") {
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
_("signupform").innerHTML = "OK " + u + ", check your email inbox and junk mail box at <u>" + e + "</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u=" + u + "&e=" + e + "&p=" + p1 + "&c=" + c + "&g=" + g);
}
and here is the form:
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once( "php_includes/template_country_list.php"); ?>
</select>
<div>
<br>
<br>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<br>
<br>
<h3>Please read the Terms and Conditions (opens a new window)</h3>
<a href="iLOVEiTtermsandCONS.pdf" title="Terms and Conditions" target="_blank">
<p>Terms and Conditions</p>
</a>
</div>
<br />
<br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
any ideas what could be wrong? I'm not good with java script at all
Thanks in advance.
I don't know what does _(" ").value mean. But if you change this style to document.getElementByid(" "), it works.

Categories

Resources