returning and recieving boolean - javascript

I need help with returning a boolean value from my validateItems() function. And my addPatrons() function (which calls the validateItems() function) must receive the boolean value returned by validateItems() and store it in a variable named "isValid". Then i need to Check the value of isValid if it is true, then use $('myform').submit(); but if it is false, then display "Patron Not Added!" in the endmessage.
this is what i have so far, its not finished because i am lost. its probably something simple but i am not getting it.
var validateItems = function () {
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if (firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
}
var lastName = $("lastname").value;
if (lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
}
var addpatron = function (validateItems) {
var isValid =
if () {
$("myform").submit();
}
else
if () {
$("endmessage").innerHTML = "Patron Not Added!"
}
}

var validateItems = function() {
var formValid = true
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if(firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
formValid = false
}
var lastName = $("lastname").value;
if(lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
formValid = false
}
return formValid
}
var addpatron = function(validateItems) {
var isValid = validateItems ()
if (isValid ){
$("myform").submit();
}
else if (){
$("endmessage").innerHTML = "Patron Not Added!"
}
}

You have to change your form element as below
<form onsubmit="return validateAndSubmit();" >...</form>
And use the validate function as below
validateAndSubmit(){
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(invalid) return false; // prevents the form from submitting
else return true; // submits the form
}
EDIT 1
if you don't have to submit the form literally, but only perform an operation on submit you can return false always.
validateAndSubmit(){
event.preventDefault();
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(!invalid){
addPatron(); // perform add operation only when form is valid
}
return false;
}
I have made the following changes.
returning false always.
If not invalid calling the addPatron() function
Added event.preventDefault() for additional event bubbling to stop.

Related

Uncaught TypeError: Cannot read property 'value' of undefined contact form html

I'v made a contact form in HTML, The code that was written is supposed to if the form is filled out correctly, change the button from "submit enquiry" to "processing..."
The code works when I test it using dreamweaver but when i try it on wordpress using the DIVI theme im getting errors
function change()
{
var salutation = document.forms["testform"]["salutation"];
var firstname = document.forms["testform"]["firstname"];
var lastname = document.forms["testform"]["lastname"];
var email = document.forms["testform"]["email"];
var phone = document.forms["testform"]["phone"];
var address = document.forms["testform"]["address1"];
var state = document.forms["testform"]["state"];
var zipcode = document.forms["testform"]["zipcode"];
var comments = document.forms["testform"]["comments"];
var custentity_stiltz_where_did_you_hear = document.forms["testform"]
["custentity_stiltz_where_did_you_hear"];
if (salutation.value == "")
{
window.alert("fill in")
salutation.focus()
return false;
}
if (firstname.value == "")
{
return false;
}
if (lastname.value == "")
{
return false;
}
if (email.value == "")
{
return false;
}
if (phone.value == "")
{
return false;
}
if (address.value == "")
{
return false;
}
if (state.value == "")
{
return false;
}
if (zipcode.value == "")
{
return false;
}
if (comments.value == "")
{
return false;
}
if (custentity_stiltz_where_did_you_hear.value == "")
{
return false;
}
var elem = document.getElementById("buttonscriptcpf");
if (elem.value=="Submit Enquiry") elem.value = "Processing...";
else elem.value = "Submit Enquiry";
return true;
}
Uncaught TypeError: Cannot read property 'value' of undefined

I am trying to make a login screen with javascript but it does not load when open the page

I have made 2 variables named username and password and I want to test if they are both true but the prompt does not seem to pop up. I do not understand, I also am pretty new to code and really want to learn how to do this
var 1 = false;
var 2 - false;
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
1 = true;
} else {
1 = false;
}
if (password == "Wout2003!") {
2 = true;
} else {
2 = false;
}
};
if (1 = false && 2 = false) {
alert("Wrong Password and Username!");
login();
}
There is so much wrong with your code, this should work though.
What you got wrong is:
You cannot set variables using the - operator
You cannot compare in an if-statement using single =
You cannot name variables with numbers.
var unc = false; // username correct
var pwc = false; // password correct
while (!login());
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
unc = true;
} else {
unc = false;
}
if (password == "Wout2003!") {
pwc = true;
} else {
pwc = false;
}
if (unc && pwc){
return true;
} else {
return false;
}
};
var 1 = false;
means that a variable called 1 will get the value of false. But this is syntactically incorrect. It is invalid to name your variables with integer names. You are also confused about the meaning of =, which is the assignment operator. Let's see a simplified solution:
var uCorrect = false;
var pCorrect = false;
function login() {
uCorrect = (prompt("Username") == "wouterXD");
pCorrect = (prompt("Password") == "Wout2003");
if ((!uCorrect) && (!pCorrect)) {
alert("Wrong Password and Username!");
}
return uCorrect && pCorrect;
}
while (!login());
Or an extremely simplified solution, if you do not need to store these data:
function login() {
return (prompt("Username") == "wouterXD") && prompt("Password") == "Wout2003";
}
while (!login());
So many things are wrong with this code...
First of all, never name your variables as integers... so rename them to something more... suitable.
Secondly, your var 2 is wrong. You've got a subtraction sign not an equals.
Least but not last, your logical operator is also wrong.
Single equals sign is assigning values, in your if statement you should check if they are the same, so a double sign is needed like so
if(firstVariable == false && secondVariable == false){
}
You won't achieve the functionality you want anyway after correcting those mistakes. The last operator (the one I posted above) is outside the function body, i.e. it won't execute when the function is ran.
var firstVariable = false;
var secondVariable = false;
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
firstVariable = true;
} else {
firstVariable = false;
}
if (password == "Wout2003!") {
secondVariable = true;
} else {
secondVariable = false;
}
if (firstVariable = false && secondVariable = false) {
alert("Wrong Password and Username!");
login();
}
};

Add another function to current JavaScript code?

Can someone please tell me how to add my below JavaScript (function validateEmail() to the JavaScript I already created (function validateForm()? I need to combine the 2 into one. What I did was create a JavaScript to create error messages, then my new one creates an error message if the Email field was typed incorrectly. The longer JavaScript is what needs the shorter one. Do I just add an else if, if than? I am new to JavaScript. Thank you for those that help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
NEW JAVASCRIPT
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}
Your final function should look like below:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
ret &= validateEmail();
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}
EDIT
If you can not (or dont want to) change validateForm function to include call to validateEmail then you can specify both functions in the form onsubmit
onsubmit="return validateForm() && validateEmail()"
Your form validation script simply needs to call your additional function as an additional test.
Try adding this to the end of your main function:
if(!validateEmail()) {
// error code
ret=false;
}
else {
// ok
}
return ret;

Form doesn't return true and won't send to PHP

So the validation for the form works, but I cannot get it to send to the php file. I'm assuming it has something to do with the return false/true and the end.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '')
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
if (email == '')
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
if (msg == '')
{
$('.msgerror').html('What can we help you with?').fadeIn(1000);
}
return false;
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
I think your last section of code should read like this:
if($.trim($('.nameerror').text()) == '')
{
// You can do stuff here first if everything is good.
return true;
}
else
{
// Or you can do stuff here for a failed submission.
return false;
}
You are exiting the function before the last if statement is checked.
You must use this code:
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '') {
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
return false;
}
if (email == '') {
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
return false;
}
if (msg == '') {
$('.msgerror').html('What can we help you with?').fadeIn(1000);
return false;
}
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
Instead of checking to see if a particular element has html in it... why don't you just set a flag? This makes everything a bit more simplistic.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
var flag = true;
//do this for each of your if statements
if(there is an error case) {
//do whatever you want to the DOM
flag = false;
}
return flag;
}

why does javascript skip some of my functions?

when i run this program the validatePhone();, validateAddress(); and validateCity(); are completely skipped, why? heres my JS:
function validatePage()
{
var valid = false;//sets valid.
var msg = "";//sets message to blank.
validateFname();
function validateFname()
{
var fnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateLname();
}
function validateLname()
{
var lnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(lastName.value.match(lnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePhone();
}
function validatePhone()
{
var nameTxt = /^[0-9]+$///sets valid inputs for recipient name.
if(Phone.value.match(nameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateAddress();
}
function validateAddress()
{
var addressTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(address1.value.match(addressTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateCity();
}
function validateCity()
{
var cityTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(cityTown.value.match(cityTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePostcode();
}
function validatePostcode()
{
var postcodeTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(postcode.value.match(postcodeTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
}
if(valid == true)
{
window.open("checkout_step_5.html");
}
else
{
msg="Not all required fields were filled."
alert(msg);
return false;
}
}
i checked for spelling mistakes and there is none well none that i have noticed i really dont know why this isnt working?
Try putting entire code in try catch as of now I did not get any exception
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validatePage()
{
try{
var valid = false;//sets valid.
var msg = "";//sets message to blank.
validateFname();
function validateFname()
{
var fnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateLname();
}
function validateLname()
{
var lnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(lastName.value.match(lnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePhone();
}
function validatePhone()
{
var nameTxt = /^[0-9]+$///sets valid inputs for recipient name.
if(Phone.value.match(nameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateAddress();
}
function validateAddress()
{
var addressTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(address1.value.match(addressTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateCity();
}
function validateCity()
{
var cityTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(cityTown.value.match(cityTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePostcode();
}
function validatePostcode()
{
var postcodeTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(postcode.value.match(postcodeTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
}
if(valid == true)
{
window.open("checkout_step_5.html");
}
else
{
msg="Not all required fields were filled."
alert(msg);
return false;
}
}catch(e){
alert(e);
}
}
</script>
</head>
<body onload="validatePage()">
</body>
</html>
And another suggestion if Valid becomes false once please break through the function using return. No Point in checking always if one parameter is false.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
return;
}

Categories