Only display 'All fields must be completed' error once - javascript

I'm trying to make a page out of javascript. I'm pretty new to all this, so bear with me.
I have a form, and when you press submit I have the following bit to see if the fields are left blank:
function calculatePrice()
{
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var norepeat = false;
if (norepeat==false && (GasPrice =="" || Distance =="" || Mileage ==""))
{
var para=document.createElement("p");
para.setAttribute("class", "error");
var node=document.createTextNode("All fields must be completed");
para.appendChild(node);
var element=document.getElementById("content");
element.appendChild(para);
var norepeat = true;
}
I created the error as a paragraph tag that appears. The problem is that when I press submit more than once, it writes the error message every time. I tried the norepeat variable thing, but it doesn't seem to be working. Any help?

Though I'm not completely sure your intentions, it'd have to look something more like:
var norepeat = false;
function calculatePrice() {
if(!norepeat && (/* other conditions here */)) {
norepeat = true;
}
return !(/* other conditions above */);
}
Where norepeat is defined in a global scope. Also, remember to use === as opposed to ==. And trimming the string before testing it wouldn't be a horrible idea...
But, wouldn't you want the errors to still persist if the user hasn't corrected them - isn't that the point of validation?

I think what you are trying to do is this. This assumes you add a new div "myError" that holds your error message. You'll also need to consider not submitting the form too if validation doesn't pass.
function calculatePrice() {
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var error = document.getElementById("myError");
if (GasPrice == "" || Distance == "" || Mileage == "") {
error.style.display = "block";
return false;
}
else {
error.style.display = "none";
return true;
}
}

Related

Is it possible to add show password functionality in login form of sylius? This script is not working

function myFunction() {
var showpass = document.getElementsByClassName('lpass');
if (showpass.type === "password") {
showpass.type = "text";
} else {
showpass.type = "password";
}
}
This script is not working. In console.log('') it is skipping to else condition directly.
Your var showpass = document.getElementsByClassName('lpass'); returns an array so use the 0 index to get the first match.
var showpass = document.getElementsByClassName('lpass')[0];
You can see more about the function here, https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

If/else syntax on password verification in javascript

I'm fairly new to javascript and trying to list out the characters missing from a failed password to tell users what they need to input.
window.onload = function()
{
var info = document.getElementById("info");
var test = document.getElementById("myForm").test;
test.onclick = function(e)
{
e.preventDefault();
var pw = document.getElementById("myForm").pw.value;
var formula = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,}/;
if(formula.test(pw))
{
document.getElementById("myForm").submit();
}
else if pw.match(/\d/g) == null {
info.innerHTML = "You need a number";
console.log(pw.match(/\d/g))
} else {
info.innerHTML = "You need a number."
}
};
};
The above is just a first run through of checking if the user inputted a password with now numbers. But I keep getting an
Uncaught SyntaxError: Unexpected identifier
in chrome dev tools with the pw.match portion underlined. I've looked elsewhere online and my syntax looks correct. Where am I going wrong?
You need some parenthesis
else if (pw.match(/\d/g) == null) {
// ^ ^
You need parentheses around the condition of your if block.
else if (pw.match(/\d/g) == null) {
...
According to:
http://www.w3schools.com/js/js_if_else.asp
You have missed ( and ) in else if.

JavaScript if else statements to display html label

I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.

How do I get two JavaScript references to the same HTML-form to work?

I'm having trouble validating an HTML form with JavaScript. On their own they each work, but together they don't.
This works:
// Make sure the e-mail address is valid
function validateEmail(mailform,email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
if(reg.test(address) == false) {
alert('E-mail not valid');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateEmail('mailform', 'email');"
And this works:
// Make sure the message is long enough
function validateBody(mailform,mailbody) {
var msg = document.forms[mailform].elements[mailbody].value.length;
if (msg < 3) {
alert('Too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateBody('mailform', 'mailbody');"
But this doesn't work:
// Make sure the e-mail address is valid AND that the message is long enough
function validateForm(mailform,email,mailbody) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
var msg = document.forms[mailform].elements[mailbody].value.length;
if(reg.test(address) == false) {
alert('Please enter a valid e-mail address');
return false;
} else if (msg < 3) {
alert('Text too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateForm('mailform', 'email', 'mailbody');"
Why?
As I said, they work each on their own, but even as different functions, they don't work together.
If you have two functions which work, why not use those?
function validateForm(mailform,email,mailbody) {
var addressValid = validateEmail(mailform,email);
var bodyValid = validateBody(mailform,mailbody);
return addressValid && bodyValid
}
The return will only return true if both tests are true. The advantage of this method is (as well as being likely to work) that it's easily extended and easily maintained.
If you only want one alert if there are two errors, then you'll need to test addressValid and call bodyValid only if required.
Use if (msg < 3) instead of else if (msg < 3) .
You don't need to use javascript: in the onsubmit attribute, remove that part.
Also, you would benefit greatly from using a JavaScript library such as jQuery.

Adding a location to a javascript timetable

feel free to launch abuse at me if I have missed a question that expains this. I'm pretty new to JS aswell.
I'm building a timtable for shuttle buses to and from our offices. I wanted to add a new location.
My current code is this:
function changeTimes (selectedOption) {
var myTT = document.getElementById("timeTable");
var myLocs = document.getElementById("Locations");
if (selectedOption=='1') {
myTT.innerHTML = brdepStr;
myLocs.innerHTML = 'Bath Road';
} else {
myTT.innerHTML = badepStr;
myLocs.innerHTML = 'Buckingham Avenue';
I then changed it to the following, which didn't work. Being a complete newbie to JS I'm guessing you can't have two "else" statements in a row?
function changeTimes (selectedOption) {
var myTT = document.getElementById("timeTable");
var myLocs = document.getElementById("Locations");
if (selectedOption=='1') {
myTT.innerHTML = brdepStr;
myLocs.innerHTML = 'Bath Road';
} else {
myTT.innerHTML = badepStr;
myLocs.innerHTML = 'Buckingham Avenue';
} else {
myTT.innerHTML = bwdepStr;
myLocs.innerHTML = 'Brunel Way' ;
}
Really appreciate any help. Thanks.
As #Mkilmanas said, there can be no 2 else on the same if block (else will always be executed if all previous if/else if statements are not executed, so if you need 2 elses, you can just cut the code from the second else into the first else). Change the first else to else if(selectedOption == '2') and you should be okay for this part :)

Categories