Why isn't this working javascript? - javascript

I am using this to detect errors on my form...
var error = false;
if (val === '') {
error = true;
}
if (error = true) {
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
Simple really but not working, am I missing something stupid? variable error is default false.
If an error is found it is true.
If error is found to be true it prevents the form being submitted?

var error = false;
if (val === '') { // <<< This checks type first, then value
// An empty '' variable is not type-equivalent
// to a (boolean) false value
error = true;
}
if (error = true) { // <<< You're setting a variable here, which means
// means that you're testing if the variable
// assignment itself is successful, you'll get
// a true result in most cases, and except with
// things like while loops, you shouldn't use this
// form.
// Maybe you want == (falsy)? Or === (type-checked)?
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}

You should do the checking in the submit event handler:
$('#joinForm').submit(function(event) {
var error = false;
if (val === '') {
error = true;
}
if (error) {
event.preventDefault();
}
});

Related

Form validation before POST Request

So I have 2 functions, one is a async function that is basically a HTTP Post Request, the other one is a form validation. I want the POST Request function to trigger only if the form validation function returns true. The form validation looks like this:
regForm.addEventListener('submit', function(event){
if (checkInputs()) {
// trigger post request function
}
})
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
}
But this doesn't seem to work, it doesn't trigger the POST Request function.
inside function checkInputs(), create a variable let check = true, assign false to this variable in every if statement:
if (usernameValue === '') {
setError()
check = false;
}
return check; at the end of function.
It triggers, because you don't return anything from the checkInputs function.
You need to return boolean /true or false/.
Something like:
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
let check = true;
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
return check;
}

Cant check boolean in javascript

I am getting values from a model, but while checking the values it always goes in to the else part of the conditions. I am alerting the values I am getting and they are correct, but in the if condition it doesn't get satisfied. I even tried with ===.
$(document).ready(function() {
var mark = new Boolean(#Model.isMarketing);
var revenue = new Boolean(#Model.isRevenue);
var staff = new Boolean(#Model.isStaff);
if (revenue == true) {
$("input[name=isRevenue][value='isRevenue']").prop("checked", true);
} else if (staff == true) {
$("input[name=isRevenue][value='isStaff']").prop("checked", true);
} else if (mark === true) {
$("input[name=isRevenue][value='isMarketing']").prop("checked", true);
} else {
$("input[name=isRevenue][value='None']").prop("checked", true);
}
});
I assume that you're getting not true or "true" from #Model.isMarketing, #Model.isRevenue etc.
And never use the === in condition when you using new Boolean(true) it won't equal true with using ===.
I wanna suggest you several approaches:
1. Use !! instead of new Boolean(#Model.isMarketing);
e.g.
var mark = !!#Model.isMarketing;
2. Just remove new Boolean() and use if like:
var mark = #Model.isMarketing;
if(mark) {
//do smth.
}
else {
//do smth else
};
Also I wanna suggest how to improve your code.
$(document).ready(function () {
var trueMark = 'True';
var mark = trueMark === #Model.isMarketing;
var revenue = trueMark === #Model.isRevenue;
var staff = trueMark === #Model.isStaff;
var value = 'None';
if (revenue) {
value = 'isRevenue';
}
else if (staff) {
value = 'isStaff';
}
else if (mark) {
value = 'isMarketing';
}
$("input[name=isRevenue][value="+ value + "]").prop("checked", true);
});
Please, make sure that you're getting right values from #Model

jQuery - Checking if array is empty or has attributes

I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})

how to make cookies and remember answer for iphone/android devices?

I have this code in my index.html
if((navigator.userAgent.match(/iPhone/i)) ) {
if (document.cookie.indexOf('iphone_redirect=false') == -1) {
if (confirm('for your device exist iphone app')) {
window.location = 'https://itunes.apple.com/us/app/....';
}
}
}
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf('android') > -1;
if(isAndroid) {
if (confirm('for your device exist iphone app')) {
window.location = 'https://play.google.com/store/apps/details?id=...';
}
}
But i don't know how to make cookie to remember my answer. If user click "cancel" or "OK" to remember "cancel" or "OK" until user clean cache.
Do you have idea how to make cookie to remember answer?
Using localStorage (phrase it so the default is falsey)
// save a flag
window.localStorage.setItem('iphone_no_redirect', 'true'); // any truthy string
// check a flag
if (window.localStorage.getItem('iphone_no_redirect')) {
// this has a truthy value
} else {
// this has a falsey value ("" or null)
}
// remove a flag
window.localStorage.removeItem('iphone_no_redirect');
// make flag falsy without removing it, set to ""
window.localStorage.setItem('iphone_no_redirect', '');
You can check against null if you want to know if a flag is set and falsey
// flag set but falsey
var x = window.localStorage.getItem('iphone_no_redirect');
if (!x && x !== null) { // x is falsey, x is not null
// ...
}
Combining this with a confirm,
function ask(question, key, overwrite) {
var response;
if (!overwrite) { // if not overwriting, check first
response = window.localStorage.getItem(key);
if (response !== null) { // has been asked before
if (['', 'false', 'no', '0', 'null', 'undefined'].indexOf(response) !== -1)
return false; // negative answers
return true; // anything else is a positive answer
}
}
if (overwrite === 2) { // easy cleanup
window.localStorage.removeItem(key);
return; // die
}
// not been asked before or we are overwriting previous answer
response = confirm(question);
window.localStorage.setItem(key, response.toString()); // "true" or "false"
return response;
}
In action
console.log(ask('Are you human?', 'is_human')); // this causes confirm dialog
console.log(ask('Are you human?', 'is_human')); // this doesn't need to ask
// changing a previous answer
console.log(ask('Are you human?', 'is_human', 1)); // this causes confirm dialog again
// cleanup
ask(null, 'is_human', 2); // (don't need question for this)

Javascript file getting syntax error

I have been looking at this code for too long and just can't see what I am missing. The error states that there is a syntax error on the very last line, I have checked all of my braces but cannot seem to find it. Can anyone help me to find it?
window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');
// if the form is found...
if (form) {
// obtain error fields
var aname = $('accountname');
var anumber = $('accountnumber');
var cname = $('cardname');
var cnumber = $('cardnumber');
var security = $('securitycode');
var zip = $('zipcode');
// Set the default status
var isValid = true;
// input error function for the error messages
var addError = function (field, msg) {
field.addClass('error'); // Add error class to field
var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
error.set('text', msg); // error text msg
error.inject(field, 'after'); // Insert error message after field
};
// detach error function used to delete any error messages and remove the error class
var removeError = function (field) {
field.removeClass('error'); // Remove error class from form fields
var error = field.getParent().getElement('span'); // find any existing error messages
// destroy if error message
if (error) {
error.destroy();
}
};
// insert submit form event
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
form.addEvent('submit', function (e) {
// Test name length
if (anumber.get('value').length === 0) {
isValid = false;
addError(anumber, accountnumberError);
} else {
isValid = true;
removeError(accountnumber);
}
form.addEvent('submit', function (e) {
// Test name length
if (cname.get('value').length === 0) {
isValid = false;
addError(cname, nameError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (cnumber.get('value').length === 0) {
isValid = false;
addError(cnumber, numberError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (securitycode.get('value').length === 0) {
isValid = false;
addError(securitycode, securityError);
} else {
isValid = true;
removeError(securitycode);
}
form.addEvent('submit', function (e) {
// Test name length
if (zipcode.get('value').length === 0) {
isValid = false;
addError(zipcode, zipError);
} else {
isValid = true;
removeError(zipcode);
}
// If form invalid then stop event happening
if (!isValid) {
e.stop();
}
});
}
});
You're missing the end curly brace and closing paranthesis for each form.addEvent('submit', function (e) {. Also, you could combine them into a single handler. Using a beautifier helps you easily find if these types of syntax errors.
Example for one of them
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
}); // <- you don't have that
On a side note, your var aname = $('accountname'); (and subsequent lines) look wrong. You probably mean to select it by id; use $('#accountname'). And I'm not aware of any addEvent function. I'm assuming you're using some other library, but for reference with jQuery you should use .on(event, handler)

Categories