I am learning Angular right now and i have an error. I have a button and when i click this button i increase this variable by 1.
checkNumber=0;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
}
Now i want to show if the current "checkNumber" is even or not so i created the following variable:
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven == false;
}
else{
this.isEven == true;
}
console.log(this.isEven);
}
The problem is, that this function alway returns false no matter what the actual number is. (I trigger the increaseLength() function with a button click).
When you want to assign value to a variable you're writing only one = and not ==, when you want to check if it equals to something then use ==
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven = false;
}
else{
this.isEven = true;
}
console.log(this.isEven);
}
This should work but I prefer to use this function, much more shorter:
function isEven(n) {
return n % 2 == 0;
}
If it returns true so it will be even if not it will be odd so just to add one if.
this.isEven == false; This should be an assignment here , rather you are checking for condition in your code. It should be :
this.isEven = false;
and
this.isEven = true;
It should be an assignment to this.isEven:
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven = false;
}
else{
this.isEven = true;
}
console.log(this.isEven);
}
Also you can massively simplify your code:
isEven = false;
increaseLength(event: any) {
this.checkNumber += 1;
this.isEven = this.checkNumber % 2 === 0;
console.log(this.isEven);
}
Related
This is a code to validate a credit card number regarding to given requirements. I made the code in a way that fits all check functions in the main function and it is working well in that way. However I wanted to tidy up my code a bit and make it better practice so the code is like this now. I think I have a part of functions that I still couldn't understand fully. Can you please tell me what is my mistake here?
Any input appreciated.
'use strict';
let cardNumLength = getLength();
let isNumOnly = /^\d+$/.test(cardNum);
let isLastDigitEven = isEndEven();
let isSumValid = isSumGreaterThan16();
let allDigitsNotSame = allEqualCheck(cardNum);
let errorArray = [];
function cardNumValidator(cardNum) {
if (cardNumLength, isNumOnly, isLastDigitEven, isSumValid, allDigitsNotSame) {
console.log(`"${cardNum}" is a valid credit card number.`);
return
}
return errorArray;
}
// getLength function to check if the number has 16 digits
function getLength(cardNum) {
//console.log(cardNum.length); //debugging
if (cardNum.length == 16) {
return true;
}
return false;
}
// to check the final digit if its even
function isEndEven(cardNum) {
if (cardNum[cardNum.length - 1] % 2 == 0) {
return true;
}
return false;
}
// to check if the sum of the digits are greater than 16
function isSumGreaterThan16(cardNum) {
let intCardNum = parseInt(cardNum);
let sum = 0;
for (let i = 0; i < cardNum.length; i++) {
sum = parseInt(sum) + parseInt(cardNum[i]); //parseInt() converts string into number
}
if (sum > 16) {
return true;
}
return false;
}
function allEqualCheck(cardNum) {
if (cardNum.split('').every(char => char === cardNum[0])) {
return false;
}
return true;
}
/* using switch statement to final validation regarding to the requirements those checked seperately by previous inner functions*/
function isValidError() {
if (cardNumLength === false) {
errorArray.push('Number must be 16 digits!');
} else if (isNumOnly === false) {
errorArray.push('Invalid characters!');
} else if (isLastDigitEven === false) {
errorArray.push('Odd final number!');
} else if (isSumValid === false) {
errorArray.push('Sum less than 16!');
} else if (allDigitsNotSame === false) {
errorArray.push('All numbers can not be the same!');
}
return errorArray;
}
cardNumValidator('9999777788880000'); //valid number example
cardNumValidator('6666666666661666'); //valid number example
cardNumValidator('a92332119c011112'); //Invalid number example
cardNumValidator('4444444444444444'); //Invalid number example
cardNumValidator('1111111111111110'); //Invalid number example
cardNumValidator('6666666666666661'); //Invalid number example
In the very first line you are not passing any arguments to the getLength function.
I'm using global variables like you did, but set them depending on the cardNum.
The cardNumValidator function will now always return an error array, which will have length zero when there is no error. When there are multiple errors, the errorArray will have all of them, not just a single one.
'use strict';
let cardNumLength = false;
let isNumOnly = false;
let isLastDigitEven = false;
let isSumValid = false;
let allDigitsNotSame = false;
let errorArray = [];
function cardNumValidator(cardNum) {
cardNumLength = getLength(cardNum);
isNumOnly = /^\d+$/.test(cardNum);
isLastDigitEven = isEndEven(cardNum);
isSumValid = isSumGreaterThan16(cardNum);
allDigitsNotSame = allEqualCheck(cardNum);
errorArray = [];
isValidError();
if (errorArray.length == 0) {
console.log(`"${cardNum}" is a valid credit card number.`);
} else {
console.log(`"${cardNum}" is an invalid credit card number.`);
console.dir(errorArray);
}
return errorArray;
}
// getLength function to check if the number has 16 digits
function getLength(cardNum) {
//console.log(cardNum.length); //debugging
if (cardNum.length == 16) {
return true;
}
return false;
}
// to check the final digit if its even
function isEndEven(cardNum) {
if (cardNum[cardNum.length - 1] % 2 == 0) {
return true;
}
return false;
}
// to check if the sum of the digits are greater than 16
function isSumGreaterThan16(cardNum) {
let intCardNum = parseInt(cardNum);
let sum = 0;
for (let i = 0; i < cardNum.length; i++) {
sum = parseInt(sum) + parseInt(cardNum[i]); //parseInt() converts string into number
}
if (sum > 16) {
return true;
}
return false;
}
function allEqualCheck(cardNum) {
if (cardNum.split('').every(char => char === cardNum[0])) {
return false;
}
return true;
}
/* using switch statement to final validation regarding to the requirements those checked seperately by previous inner functions*/
function isValidError() {
if (cardNumLength === false) {
errorArray.push('Number must be 16 digits!');
}
if (isNumOnly === false) {
errorArray.push('Invalid characters!');
}
if (isLastDigitEven === false) {
errorArray.push('Odd final number!');
}
if (isSumValid === false) {
errorArray.push('Sum less than 16!');
}
if (allDigitsNotSame === false) {
errorArray.push('All numbers can not be the same!');
}
return errorArray;
}
cardNumValidator('9999777788880000'); //valid number example
cardNumValidator('6666666666661666'); //valid number example
cardNumValidator('a92332119c011112'); //Invalid number example
cardNumValidator('4444444444444444'); //Invalid number example
cardNumValidator('1111111111111110'); //Invalid number example
cardNumValidator('6666666666666661'); //Invalid number example
Attempting to complete the algorithms on freeCodeCamp. I eventually found an approach that works, but i still don't understand why this method did not work for all cases.
function palindrome(str) {
var alphaNumericStr = str.replace(/\W/g,"");
var lowerCaseAlphaNumericString = alphaNumericStr.toLowerCase();
var arr = lowerCaseAlphaNumericString.split("");
arr.reverse();
var reversedString = arr.join("");
if(str === reversedString){
return true;
}
return false;
}
palindrome("race car");
You're comparing a string which has been stripped of spaces and converted to lowercase to the original string. Replace your conditional with:
if(lowerCaseAlphaNumericString == reversedString){
rethrn true;
}
return false;
Here's a little refactor if you're interested:
// ...
var reversedString = arr.join('');
return lowerCaseAlphaNumericString == reversedString;
demo
This is where you are going wrong if(str === reversedString)
Try this:
if(lowerCaseAlphaNumericString === reversedString) {
return true;
}
return false;
}
There could be another approach. In this approach, the corner cases are handled separately.
function check_Palindrome(input_str){
var astr = input_str.toLowerCase().replace(/\W/g,'');
var acount = 0;
if(astr==="") {
console.log("Not Palindrome.");
return false;
}
if ((astr.length) % 2 === 0) {
acount = (astr.length) / 2;
} else {
if (astr.length === 1) {
console.log("Palindrome.");
return true;
} else {
acount = (astr.length - 1) / 2;
}
}
for (var x = 0; x < acount; x++) {
if (astr[x] != astr.slice(-1-x)[0]) {
console.log("Not Palindrome.");
return false;
}
}
console.log("Palindrome.");
return true;
}
I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.
I am using a jQuery script and the main part is below. It allows me to select up to 4 items. Until there are 5 selections made, there is an error message.
How can I change this so that the error message appears if the choices are less than 2 and more than 5, and the success message is shown when the choices are between them?
if ($(this).multiselect("widget").find("input:checked").length > 5) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
You can get the number of checked items in to a local variable and then use a compound if statement that does multiple comparisons on it:
var checkedItemsLength = $(this).multiselect("widget").find("input:checked").length;
if(checkItemsLength < 2 || checkItemsLength > 5 ) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
function doSomeChecking() {
// assuming 'warning is a reference to some div or span
var warning = $('#warning');
var numChecked = $(this).multiselect("widget").find("input:checked").length;
if (numChecked > 5) {
warning.addClass("error").removeClass("success").html("You cannot check more than five boxes!");
return false;
} else if (numChecked < 2) {
warning.addClass("error").removeClass("success").html("You must check at least two boxes.");
return false;
}
warning.addClass("success").removeClass("error").html("Life is good.");
return true;
}
var selections = $(this).multiselect("widget").find("input:checked");
if(selections.length < 2) {
warning.addClass("error").removeClass("success").html("You have to check atleast two checkboxes!");
return false;
} else if (selections.length > 5) {
warning.addClass("error").removeClass("success").html("You can not check more then five checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
if(foo < 2 || foo > 5){
//do something
}else {
//do something else
}
I want to validate multiple functions, and for each one returning false, do some animations.
Here's the code:
function validarChido(){
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
$('#form').submit(function(){
if( validarChido() && validarEx() )
{return true }
else
{return false; }
});
When I send the form, I only see the first function doing the color animation, obviously because the form validation IF statement doesn't evaluate the next function because the first resulted in false here if( validarChido() && validarEx() )
Is there a way to evaluate all the functions and see the animation in each one and then send the form if everything is true?
Instead of returning false or true do something similar to the following:
function validarChido() {
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
$('#form').submit(function(){
var check = validarChido();
check += validarEx();
if( check == "" )
{return true }
else
{return false; }
});
It can be something like this:
$('#form').submit(function(){
var validarChidoResult = validarChido(),
validarExResult = validarEx();
if( validarChidoResult && validarExResult )
{return true }
else
{return false; }
});
var result = validarChido();
result = validarEx() && result;
return result;