Change color depending on value - javascript

I don't why this is not working. Can somebody tell me what is the problem with this?
var x = $('#clicked_info').val();
if(x == 1) {
$('#companyname_ph').css({'color':'yellow'});
}
else if(x == 2) {
$('#companyname_ph').css({'color':'red'});
}

You need to use parseInt to convert a string to an integer.
var x = $('#clicked_info').val();
if(parseInt(x) == 1){
$('#companyname_ph').css({'color':'yellow'});
} else if(parseInt(x) == 2){
$('#companyname_ph').css({'color':'red'});
}
OR use string comparison
if(x == '1'){

val returns a string
x == 1 shoulb be x == '1'
x == 2 should be x == '2'
Or you can convert x to int using the following.
var x = $('#clicked_info').val();
x = parseInt(x);

like the other folks here have noted, you should use parseInt when you want to convert a string representation of an integer to a number type. I would add that you should provide a radix to parseInt because if you don't, you may get unexpected results if your string starts unexpectedly with "0x" :)
try doing:
var x = parseInt($('#clicked_info').val(), 10)

Related

JavaScript: Hex to decimal converter error

I have been making a custom function for converting hex to decimal from my scratch project:
function Hex2Decimal(hex){
var deci = 0;
var num = 1;
var hexstr = String(hex);
hexstr = hexstr.toLowerCase();
var expon = 0;
for(var i = 0; i < hex.length; i++){
expon = Math.pow(16,hexstr.length - (num+1));
if(hexstr[num+1] === "a"){
deci = (10*expon)+deci;
}else if(hexstr[num-1] === "b"){
deci = (11*expon)+deci;
}else if(hexstr[num-1] === "c"){
deci = (12*expon)+deci;
}else if(hexstr[num-1] === "d"){
deci = (13*expon)+deci;
}else if(hexstr[num-1] === "e"){
deci = (14*expon)+deci;
}else if(hexstr[num-1] === "f"){
deci = (15*expon)+deci;
}else if(hexstr[num-1] != "undefined"){
deci = (Number(hexstr[num-1])*expon)+deci;
}
num = num + 1;
}
return deci;
}
but when I put "BC324240" into it, it returns the value '197338148' instead of '3157410368.'
When converting the value back to hex, I get 'BC32424.' For some reason, that I need help finding, the '0' in it is completely 'ignored.'
Also noticed that using '10' returns 1...
The following built-in function will do the conversion for you:
dec = parseInt('0x' + hexstr,16);
Just be sure that the number to convert is less than the maximum safe JavaScript integer:
(2^53 - 1) = 0x1fffffffffffff = 9007199254740991.
If you need to work with larger numbers, look at the code here:
https://codegolf.stackexchange.com/questions/1620/arbitrary-base-conversion
I didn't write it, so don't ask me to explain it
You're missing the last position (the digit you should multiply by 16^0) because your call:
expon = Math.pow(16, hexstr.length - (num+1));
is off by one, should be:
expon = Math.pow(16, hexstr.length - num);

Simple javascript if statement with charAt is not working

Its simple, if a user enters a number that does not beggin with 6 or 9, he gets error:
console.log($(this).val().charAt(0));
if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){
x=false;
}else {
x=true;
}
Console.log correctly displays the first character.. that means the value exists..
But no matter if I type 6 or 7 or 9, i will always get false... Why?
Whatever the value of somevar,
somevar!=6 OR somevar!=9
is always true.
The best solution here would probably be a regular expression:
var x = /^[69]/.test($(this).val());
You need to invert the logic conditions as both states cannot possibly be true at the same time, so x is always set to false. Try this:
var chr = $(this).val().charAt(0);
if (chr == '6' || chr == '9') {
x = true;
} else {
x = false;
}
From there you can now see that you don't even need the if condition as you can set x directly, like this:
var chr = $(this).val().charAt(0);
var x = chr == '6' || chr == '9';

Best way to check if a number contains another number

For example if the number 752 contains the number 5? Whats the best way to check? Convert to string or divide into individual digits?
Convert to string and use indexOf
(752+'').indexOf('5') > -1
console.log((752+'').indexOf('5') > -1);
console.log((752+'').indexOf('9') > -1);
Convert to string and use one of these options:
indexOf():
(number + '').indexOf(needle) > -1;
includes():
(number + '').includes(needle);
You can use 3 ways:
Check it by string contains:
var num = 752;
num.toString().indexOf('5') > -1 //return true or false - contains or not
Check by loop
var f = 2;
while(num > 0 ){
if( num % 10 == f){
console.log("true");
break;
}
num = Math.floor(num / 10);
}
Check by regular expressions
num.toString().match(/5/) != null //return true if contains
function checkNumberIfContainsKey(number, key){
while(number > 0){
if(number%10 == key){
return true;
}
number = Math.trunc(number / 10);
}
return false;
}
console.log(
checkNumberIfContainsKey(19, 9), //true
checkNumberIfContainsKey(191, 9), //true
checkNumberIfContainsKey(912, 9), //true
checkNumberIfContainsKey(185, 9) //false
);
The most efficient solution among available answers because of the complexity of this program is just O(number of digits) if number = 10235 then the number of digits = 5
You can also use "some" function.
"Some"thing like this:
function hasFive(num){
return num.toString().split("").some(function(item){
return item === "5";
});
}
and then you can call it:
hasFive(752)
Further improved is that you make a function that takes number and digit you want to check:
function hasNumber(num, digit){
return num.toString().split("").some(function(item){
return item == digit;
});
}
And then call it in similar way:
hasNumber(1234,3) //true
hasNumber(1244,3) //false
So that way we can check any number for any digit.
I hope so "some"one will find this useful. :)

How to ensure that data submitted is a valid numerical pair?

I receive a string.
It should be in the format:
number,number
for example:
34.798,52.123
How can I verify that the number is in this format ? I need to assign it to some vars, and do some calculation. But since it is javascript (node.js), someone may submit a function instead and try to make my app invoke it. How do I verify that a submitted string is in the above format ?
I've considered the following approach:
function checkIfValid(input){
var result = false;
input = input.trim();
var tokens = input.split(",");
if(tokens.length==2){
if(!isNaN(tokens[0]&&!isNaN(tokens[1]){
result = true;
}
}
return result;
}
Is there a better way to do this ? Can it be hacked ?
check for invariance across parseFloat
function checkIfValid(input){
input = input.trim();
var tokens = input.split(",");
if(tokens.length === 2){
var t0 = tokens[0];
var t1 = tokens[1];
return parseFloat(t0) == t0 && parseFloat(t1) == t1;
}
return false;
}
You could use JSON.parse (after wrapping in [...]) and then check you got an array of two numbers:
var x = null;
try { x = JSON.parse("[" + data + "]"); } catch (err) { x = null; }
if (x && x.constructor === Array && x.length === 2 &&
typeof x[0] === "number" && typeof x[1] === "number") {
... data is ok ...
} else {
... data is invalid ...
}
this approach also scales to other more complex cases.
The only annoying thing is that certain valid numbers for Javascript are not valid for JSON (for reasons I don't understand). For example "1." is not valid JSON (a digit is mandatory after the decimal point). You also cannot use NaNs and infinity values because that's also invalid in JSON.
The problem with your code is the edge case of isNaN('') == false; this is because '' is converted into a numerical value of 0 which can be represented.
You should parse the values first using parseFloat():
function checkIfValid(input)
{
var parts = input.split(',');
return parts.length == 2 && parts.every(function(part) {
return !isNaN(parseFloat(part));
});
}

JavaScript Conditional Statement Not Working

What's wrong with this JavaScript?
var numPackages == 0;
if (coffeeProducts <= 12) {
numPackages == 1;
} else if (coffeeProducts % 12 == 0) {
numPackages == coffeeProducts/12;
} else {
numPackages == (coffeeProducts/12) + 1;
}
Basically, it needs to calculate the number of boxes/packages necessary to ship an amount of items (12 per box). Is there a better way to do this, perhaps using round()?
== is condition.
= is assignment.
The better way is to use Math.ceil() to round to next integer.
So:
var numPackages = Math.ceil(coffeeProducts/12);
All the others explained your mistake with the comparing operator == and the assigning operator =.
The shortest way to solve it would be
var numPackages = Math.ceil( coffeeProducts / 12 );
Make each statement look like this:
if (coffeeProducts <= 12) {
numPackages = 1; // just "=", not "=="
}
Single equals (=) for assignment: x = 10
Double equals (==) for comparison: if (x == 10)
Triple equals for special cases where type is important as well as the value.
Change your two numPackages lines to a single equals and you're good to go :)

Categories