Javascript - Call Two Functions at Onsubmit - javascript

I have two functions; one that validates the form, the other executes some code if the first function returns true.
<form name="calculator" method="POST" onsubmit="return checkForm(); result(trueOrFalse);" onreset="clearForm()">
The checkForm() function is defined as follows:
function checkForm() {
var valid = true;
var radios1 = document.getElementsByName("item");
var radios2 = document.getElementsByName("postage");
if (document.getElementById("constituency").value == 0) {
document.getElementById("constituency").style.border = "1px solid #a60f28";
document.getElementById("constituency").style.borderRadius = "2.5px";
document.getElementById("conWarning").style.display = "block";
valid = false;
}
//similar code as above for other fields
trueOrFalse = valid;
return valid;
}
The result(valid) function is defined as:
function result(valid) { //use trueOrFalse as parameter
if (valid == true) {
document.getElementById("result").style.display = "none";
document.getElementById("result").innerHTML = "Yay"; //test display value
document.getElementById("result").style.display = "inline";
}
else {
document.getElementById("result").style.display = "none";
document.getElementById("result").innerHTML = "0";
document.getElementById("result").style.display = "inline";
}
return valid;
}
The goal here is to check first if the form filled out by the user is valid; if it is then produce a value to show to the user in the HTML as follows:
<div id="pound">£ <div id="result">0</div></div>
I'm not sure if the way I'm calling my two functions is correct/legal or if it is, whether the value to be display by the result(valid) function has been written correctly. The form is supposed to act as a calculator.

Instead of:
trueOrFalse = valid;
return valid;
Try this:
return result(valid);
Then remove result(trueOrFalse); from your onsubmit.

Related

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Why is nothing happening when I click on onclick button?

*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.

Form validation doesn't like me

Second edit: OH MY GODS I'M AN IDIOT!!! I was focusing on the javascript and completely neglected the lack of a "result" item in the html...Thanks to those who helped!
Edit: Thanks so far. I corrected the errors that people pointed out but it still doesn't like me. :( My html is below.
I'm following a tutorial on html.net (lesson 16 on Javascript) and I've written it exactly how it's supposed to be written. I even loaded up the javascript file of the working tutorial page and compared (was the same)...then copied it and pasted it into my file just to be sure and it still doesn't work. If anyone could offer an opinion, that'd be wonderful. Code is below:
<html>
<head>
<title>Lesson 16: form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name: </label>
<input type="text" id="txtName" name="txtName" />
</p>
<p><label for="txtEmail">Email: </label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
</body>
</html>
function init()
{
var myForm = document.getElementById("myForm");
myForm.onsubmit = validate;
}
onload = init;
function validate()
{
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid)
{
message = "Thank you, you know how to follow instructions...good for you.";
}
else if (! isRequiredNameSet)
{
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
}
else if (! isRequiredEmailSet)
{
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
}
else if (! isEmailValid)
{
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
function validateRequired(input)
{
var isValid = false;
if (input.length == 0)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function validateEmail(email)
{
var isValid = false;
if (email.indexOf("#") == -1 || email.indexOf(".") == -1)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function writeMessage(text)
{
var paragraph = document.getElementById("result");
if (paragraph.firstChild)
{
paragraph.removeChild(paragraph.firstChild);
}
paragraph.appendChild(document.createTextNode(text));
}
you have IsRequiredNameSet in the else if (in validate function), but it should be isRequiredNameSet.
NOTE: you can chage your validateRequired() ... to function validateRequired(input) { return !!input.length; }
The problem is the line myForm.onsubmit = validate();... where you are invoking the validate function instead os assigning it as a reference to onsubmit
myForm.onsubmit = validate;
The same applies to onload also
onload = init;
Then you have a problem in case of isRequiredEmailSet
function validate() {
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid) {
message = "Thank you, you know how to follow instructions...good for you.";
} else if (!isRequiredNameSet) {
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
} else if (!isRequiredEmailSet) {
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
} else if (!isEmailValid) {
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
Demo: Fiddle

loop through all fields and return false if validation of any one field fails jquery

I am facing big trouble resetting the flag variables. I am not sure where I am missing :(
I have a form with lots of text fields. I am trying to loop through all the fields and on blur of each of the field I am doing some validations. If any of the validation for any of the field fails it should not submit the form. But now I am having a big trouble doing this. If I have 3 fields and the first value I have entered wrong and next two fields if I have given correct, its submitting the form which should not be. Can somebody please help me in this?
var globalValid = false;
var validators = {
spacevalidation: function(val) {
if($.trim(val) != "")
return true;
else
return false;
},
//Other validation fns
};
$('#form1 .required').blur(function(){
var input = $(this);
var tmpValid = true;
input.each(function(){
var classReturn = true;
validatorFlag = true;
input.next('ul.innererrormessages').remove();
input.removeClass('required_IE');
if(firstTime)
{
input.addClass('valid');
}
if (!input.val()) {
input.removeClass('valid');
input.addClass('required');
var $msg = $(this).attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
globalValid = false;
}
else{
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
tmpValid = (tmpValid && validators[classes[p]] (input.val())) ? tmpValid : false;
}
}
}
if(tmpValid == false){
input.removeClass('valid');
input.addClass('required');
var $msg = input.attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
}
}
});
globalValid = tmpValid;
});
$('#form1').submit(function() {
var returnValue = true;
if(globalValid )
{
returnValue = true;
}
else{
returnValue = false;
}
alert("returnValue "+returnValue);
return returnValue;
});
Using this code, if I put a wrong value for first field and correct value for the other two fields, ideally it should return false. But its returning true. I think I am not properly resetting the flag properly
Checkout this example which provides the basic premise of what needs to occur. Each time the blur event is fired you must validate all three fields and store the result of their validation to a global variable.
HTML
<form>
<input />
<input />
<input />
<button type="submit">Submit</form>
</form>
Javascript
var globalValid = false; //Global validation flag
$("input").blur(function(){
//local validation flag
var tmpValid = true;
//When one input blurs validate all of them
$("input").each(function(){
//notice this conditional will shortcircuit if tmpValid is false
//this retains the state of the last validation check
//really simple validation here, required value less than 10
tmpValid = (tmpValid && this.value && this.value < 10) ? tmpValid:false;
});
//assign the result of validating all inputs to a global
globalValid = tmpValid;
});
$("form").submit(function(e){
//This is just here to make the fiddle work better
e.preventDefault();
//check the global validation flag when submitting
if(globalValid){
alert("submitted");
}else{
alert("submit prevented");
}
});
JS Fiddle: http://jsfiddle.net/uC3mW/1/
Hopefully you can apply the principles in this example to your code. The main difference is the code you have provided does not validate each input on blur.

Categories

Resources