Adding multiple forms and inputs with onclick events using javascript - javascript

I am currently working on an website project that my friends and I would like to publish in the future. I´m currently building the html and css side of the page and need to implement dynamic events (if that's how its called) in the page for customer input.
I have a very little understanding when it comes to javascript/jquery (I am able to get a general idea of what is happening, yet my syntax comprehension is poop) and have only a basic knowledge of html and css. Now, I am aware that my inquiry is extensive and I would really appreciate any help, or pointers in the right direction!
So far the different blocks of code that I have found and tried by googling have worked for me, but only in executing individual functions (e.g.: the toggle function works but the create.element function doesn't).
This is my current html code that I am trying to modify with Javascript:
<div class="bttiendas">
<button class="btndag">Agregar</button>
<button class="btndgu">Guardar</button>
</div>
<div class="rdatos">
<form class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>
</div>
What I am trying to accomplish with Javascript is as follows:
-To be able to create with javascript both .thf and .trf forms dynamically along with every other input/button that is inside each form with clicking the .btndag button (this is an onclick event followed by create.element if I'm not mistaken).
-For the .morehf <input button> have a hide/show toggle function for .trf and anything else inside that form.
-Toggle disabled in the .crf input text boxes with the .edithf <input button>.
-To be able to erase/remove both .thf and .trf forms (their input textboxes AND the buttons .morehf .edithf .erasehf) with the .erasehf <input button>.
-And to be able to save/submit (I am not sure which is the correct term here) any added and completely filled out forms fields (for when we want to send the changes to our database).
Again I would greatly appreciate any help you could give me, and thank you in advance for your time.

You can import jquery into your solution.
For step 1: you do not make sense. Do you mean you want to load data into your form from somewhere to edit data or something? how is this dynamic? It looks like static forms on a page.
For step 2:
<input class="morehf" onclick="toggleTrf()" type="button" value="+/-" />
<script>
function toggleTrf() {
$(".trf").toggle()
}
</script>
step 3:
<input class="edithf" onclick="disableInputs()" type="button" value="Edit" />
<script>
function disableInputs() {
if($(".crf").is(":disabled");){
//jquery 1.6+
$(".crf").prop('disabled', false);
//jquery 1.5 -
$(".crf").removeAttr('disabled');
}
else {
//jquery 1.6+
$(".crf").prop('disabled', true);
//jquery 1.5 -
$(".crf").attr('disabled','disabled');
}
}
</script>
step 4: it is not clear what you mean by erase the form but you can clear the text in the inputs
<input class="erasehf" thpe="reset" onclick="clearInputs()" value="Erase" />
<script>
function clearInputs() {
$("input").val("")
}
</script>
step 5:
<form action="some/path">
<input name="someName" type="text" text="random field" value="1" />
<button type="submit">submit</button>
</form>
That submit button will submit the form to whatever path you specify in your form action. As for saving to the database etc it is impossible to guess what technology you will use to do that.sorry about code formattin im typing on a phone.

I believe I have included everything the OP wanted. The non-jQuery approach (ES6). JSFiddle
First lets add a few helper variables:
let formSets = 0;
let createForm = function(id) {
return `<form data-id='${id}' class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form data-id='${id}' class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>`;
};
Add the onclick event for the "add" function. We have to reassign the click events to the dynamically added elements or we could have done event delegation like I did for the remove button:
document.getElementsByClassName('btndag')[0].onclick = () => {
document.getElementById('a').innerHTML += createForm(++formSets);
for (let ii = 0; ii < formSets; ii++) {
document.getElementsByClassName("morehf")[ii].onclick = () => {
document.getElementsByClassName("trf")[ii].classList.toggle('hide');
}
document.getElementsByClassName("edithf")[ii].onclick = () => {
let form = document.getElementsByClassName("trf")[ii].children;
for (let i = 0; i < form.length; i++) {
let input = form[i];
if (input.disabled == true) {
input.disabled = false;
} else {
input.disabled = true;
}
}
}
}
};
Add the remove button a little differently using event delegation which allows us to target another element based on the parents target:
document.getElementById('a').onclick = function(e) {
let t = e.target;
if (t.className == 'erasehf') {
let me = t.parentNode;
let sib = me.nextElementSibling;
me.parentNode.removeChild(me);
sib.parentNode.removeChild(sib);
}
}
Finally, submit the data. This part is a little more vague simply because I am not exactly sure how you want the data formatted. But here is how you would submit the form using AJAX:
document.getElementsByClassName('btndgu')[0].onclick = function() {
Request("/linkto/save.asp").post({
//datahere
}).then(function () {
//on success
}, function () {
//on failure
});
}
Note that this uses a helper AJAX function that I made:
let Request = function(url, opt) {
// start loader
var AJAX = function(type, url, data, success, failure, cache) {
var InitRequest = new Promise(function(accept, reject) {
var request = new XMLHttpRequest(); // initiate new XMLHttpRequest
var done = false;
var compile = function(data) { //turn the data object into a usable source for the send function
var send = [];
for (var item in data) { // compile all data in "item=data" strings
send.push(item + "=" + encodeURIComponent(data[item]));
}
send = send.join("&"); // combine data to form "item1=data1&item2=dat2&item3=data3"
return send;
};
// if we choose not send any data, then the data variable will take the place of the success variable
// because of this, we have to also shift the failure function
if (typeof data === "function") {
success = data || accept;
failure = success || reject;
data = "";
} else {
success = success || accept;
failure = failure || reject;
data = compile(data);
}
if (type.toUpperCase() == 'POST') {
request.open(type.toUpperCase(), url, true);
// this header allows POST requests to work
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (type.toUpperCase() == 'GET') {
// for GET requests, we need to put all data in the url
// we would end up with test.php?item1=data1&item2=dat2&item3=data3
request.open(type.toUpperCase(), url + "?" + data, true);
} else {
console.error('Incorrect request type submitted: "' + type + '" is not supported.');
return false;
}
// in order for laravel to properly send ajax requests
request.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function() {
if (!done) {
if (request.readyState === 4) { // when the readyState == 4, we have completed the request
if (request.status === 200 || request.status === 0 /*for ff bug*/ ) {
success(request.responseText, request);
} else { //if failed
try {
request.responseJSON = JSON.parse(request.responseText);
} catch (e) {
return false;
}
failure(request);
}
// hide the loader because the request has finished
done = true;
}
}
};
// send off the request
request.send(data);
});
return InitRequest;
};
// The "opt" variable also goes into place as the
// Cache reset
if (opt && typeof opt !== "string" && typeof opt !== "boolean") {
var DEFAULTS = {
type: "GET",
data: {},
cache: false,
success: function() {},
failure: function() {}
};
var o = $.extend(DEFAULTS, opt);
return AJAX(o.type, url, o.data, o.success, o.failure, o.cache);
} else {
return {
post: function(data, success, failure, cache) {
return AJAX("POST", url, data, success, failure, cache);
},
get: function(data, success, failure, cache) {
return AJAX("GET", url, data, success, failure, cache);
}
}
}
}
A little more information about sending data via AJAX
Data in your case should correspond with the ids:
{
0: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
},
1: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
}
}

Related

Firebase not creating users [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 );
}

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 );
}

Not returning a value for some reason

Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}

Trouble using simple ajax in jsp - contents populating and then disappearing

I am using a simple jsp to populate a drop down box (with addresses as options) based on an input parameter (postcode) using ajax in javascript. The javascript code is able to pull the required data, and sets the options in the select element, but just after a fraction of second, all changes disappear and the jsp is back to its initial state. Can you help me in troubleshooting the cause of this behaviour? Thanks in advance.
main JSP code: testajx.jsp
<form name="testform" method="POST" action="testajx.jsp" >
<h1><%=a%> testing <b>Postcode Lookup</b></h1>
<br>
<br>
<input type="text" name="ziporpostalcode" size="10" maxlength="7" value="<%=ziporpostalcode%>"/>
<input type="text" name="ziporpostalcodetest" size="10" maxlength="7" value=""/>
<input type="hidden" name="searchPostCodeHidden" value="">
<input type="button" name="searchPostCode" value="Search" onclick="if(ziporpostalcode.value == ''){alert('enter postcode');}else {searchPostCodeHidden.value = 'TRUE'; this.form.submit();}">
<input type="hidden" name="searchAddressHidden" value="">
<input type="button" name="test" value="test" onclick="alert(userAddress.value);alert('<%=userAddress%>');">
<input type=image name="op_xxx" value="Search Address xxx" src="\jsp\htdocs\assets\images2011\buttons\search_address.gif" alt="Search Address" onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
<select name="userAddress" value="<%=userAddress%>" onchange="searchAddressHidden.value = userAddress.value; form.submit();">
<option>--- Select ---</option>
<%=addressOptions%>
</select>
<div id="ajax_res">a</div>
</body>
</form>
Results received from testajax.jsp:
<body>
<select name="userAddress">
<option>--- Select ---</option>
<%
String addressOptions = new String();
Picklist pl = new Picklist();
addressOptions = "";
String ziporpostalcode = request.getParameter("ziporpostalcode");
pl = PostcodeHandler.getAddressList(ziporpostalcode);
PicklistItem[] pli = pl.getItems();
//Iterator li = sAddressList.values().iterator();
for(int i=0; i<pl.getTotal(); i++)
{
addressOptions += "<option label=\""+pli[i].getPartialAddress()+"\" value=\""+pli[i].getMoniker()+"\">"+pli[i].getText()+"</option>";
session.setAttribute("addressOptions", addressOptions);
request.setAttribute("ziporpostalcode", ziporpostalcode);
request.setAttribute("searchPostCodeHidden", ziporpostalcode);
// addressOptions += "<option label='"+sAddressList.get(i).toString()+"' value='"+sAddressList.get(i).toString()+"'>"+sAddressList.get(i).toString()+"</option>";
}
String str="This is JSP string loading from JSP page in ajax, loading time :";
out.print(addressOptions);
%>
</select>
ajax javascript code is:
<script language="Javascript" type="text/javascript">
function createRequestObject(){
var req;
try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
document.getElementById("ziporpostalcodetest").value = 'response';
document.getElementById("testform").action = 'testajax.jsp';
alert('received something from Ajax');
}
}
}
You're sending an ajax request in the onclick of an <input type="image"> submit button. However, you're not blocking the button's default behaviour when the onclick is finished. The button's default behaviour is namely submitting the form where it is sitting in. You need to block the button's default behaviour by returning false in the onclick.
So, change
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
to
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value); return false;"href="#" />
Unrelated to the concrete problem, you've severe design problems with this all. I'm not sure where you've learnt HTML, JSP and Ajax, but this all looks very 90's. Make sure that you're reading up to date resources. This may be a good starting point: How to use Servlets and Ajax?
Just tired to search an error in your code. Here is my (don't foget include jQuery core):
<div id="content"></div>
<script type="text/javascript">
function updateDivContent() {
var result = jQuery.ajax({
url: "your url",
type: "POST",
async: true,
cache: false,
data: // your form data, can use serialize from jquery
});
jQuery("div#content").html(result.responseText)
}
</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