Prevent sending form with JavaScript - javascript

I have html form with action ="script.php" which sends data.
I want prevent form to being sent with JS but it does nothing and sends data.
Naslov = title
This is html:
<form name = "my_form" enctype="multipart/form-data" method = "POST" action = "skripta.php">
<div class="form-group row ">
<div class="col-md-6">
<span id="porukaTitle" class="bojaPoruke"></span>
<label for="naslov">Naslov</label>
<input type="text" name="naslov" class="form-control" id="naslov">
</div>
</form>
And this is JS:
<script type="text/javascript">
document.getElementById("slanje").onclick = function (event) {
var slanjeForme=true;
var poljeTitle=document.getElementById("naslov");
var naslov=document.getElementById("naslov").value;
if (naslov.lenght < 5 || naslov.lenght > 30) {
slanjeForme=false;
poljeTitle.style.border="1px dashed red";
document.getElementById("porukaTitle").innerHTML="Naslov vjesti mora imati između 5 i 30 znakova!<br>";
} else {
poljeTitle.style.border="1px solid green";
document.getElementById( "porukaTitle").innerHTML="";
}
if (slanjeForme != true) {
event.preventDefault();
}
}
</script>
Problem is that it always sends data.

Don't use the "click" handler, instead use the FORM's "submit" Event handler!
Create a nifty reusable validate function that will also handle the input style using classList.toggle()
Populate your validate function with the needed validators
Use finally CSS to handle error borders and messages visibility using the class is-error
Always place the error SPAN elements as siblings to a desired action element, that way when an input gets the .is-error we can target it using the CSS's General Sibling Combinator ~
No matter how many inputs you have, you don't need to write extra JS logic. Just validate the desired ones like const has_err = validate(EL("#foo"), "length");
const validate = (el, validatorName = "length") => {
const val = el.value.trim();
const isErr = {
// Basic, validates if there's value
length: () => val.length < 1,
// Validate between 5 and 30 charaters
length_5_30: () => val.length < 5 || val.length > 30,
// Add more validators
}[validatorName]();
el.classList.toggle("is-error", isErr);
return isErr;
};
const EL = (sel, EL) => (EL || document).querySelector(sel);
EL("#my_form").addEventListener("submit", function(event) {
const err_1 = validate(EL("#naslov"), "length_5_30");
const err_2 = validate(EL("#bla"), "length");
if (err_1 || err_2) {
event.preventDefault();
}
});
form .is-error {
outline: 1px dashed red;
}
form .error-message {
display: none;
color: red;
}
form .is-error ~ .error-message {
display: block;
}
<form id="my_form" name="my_form" enctype="multipart/form-data" method="POST" action="skripta.php">
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Naslov</label>
<input type="text" id="naslov" name="naslov" class="form-control">
<span class="error-message">Naslov vjesti mora imati između 5 i 30 znakova!</span>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Bla bla</label>
<input type="text" id="bla" name="bla" class="form-control">
<span class="error-message">Ovo polje ne može biti prazno!</span>
</div>
</div>
<button type="submit">Pošalji</button>
</form>

You should use a form validation function instead. In your form, add an attribute called "onsubmit". The form should look similar to this:
<form onsubmit="return checkBeforeSubmitting()"></form>
Then, you can have a function run before data is sent. If you don't want data to be sent, make the "checkBeforeSubmitting()" return false under a certain condition.
Link to more info on how to use this: https://www.w3schools.com/js/js_validation.asp

The best way to stop a form from submitted is to hook into its submit event, and do so in the javascript, rather than add javascript into the html. That would look like this:
var form = document.querySelector('form.myform');
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true ) {
e.preventDefault();
}
// else form will submit;
});
<form class="myform">
<!-- form stuff -->
<input type="submit" value="Submit">
</form>
You may also wish to submit the form from within itself, after doing the preventDefault(). You can do that by setting a flag to indicate that the check has already been processed:
const form = document.querySelector('form.myform');
var okToSubmit = false;
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true && ! okToSubmit ) {
e.preventDefault();
// do some further processing and submit again.
okToSubmit = true;
e.target.submit();
}
// else form will submit;
});

Related

JavaScript Custom Form Validation

I am new to JavaScript and tend to get stuck with some problems. I was trying to create a custom validation for a form, which consists from 4 inputs, but the code doesn't work for me. Does anyone have any ideas how can I fix it? Here is just one of the inputs:
<div class="inputWrapper">
<input class="formInput required type="text" name="Email" id="Email" placeholder="Email Address"/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div id="emailError" class="errorMessage hidden">
<i>Email cannot be empty</i>
</div>
</div>
I also have two divs that should appear, when the input is submitted with error, before that they have a class "hidden" with display none.
"use strict";
const formInput = document.querySelector(`.formInput`);
const errorImg = document.querySelector(`.errorImg`);
const errorMessage = document.querySelector(`.errorMessage`);
const input = formInput.nodeValue;
const errorOccured = function () {
errorMessage.classList.remove(`hidden`);
errorImg.classList.remove(`hidden`);
};
form.addEventListener("submit", function () {
if (input === ``) {
errorOccured();
}
});
This is how the page looks like itself:
You should read input value in the event listener function
let form = document.querySelector("#form1");
form.addEventListener("submit", function (e) {
const input = formInput.value;
if (input === '') {
errorOccured();
e.preventDefault();
}
});

Submit HTML Form to firestore with Validation without a action [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

How trigger validation on a textbox when a button is pressed?

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.

Display textbox multiple times

The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>

Validation stuck at first validation

I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />

Categories