Using == in javascript always false [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hello I use a javascript function to change my HTML background color by DI state
here's my code
function pageData() {
var DI1_STATE =document.getElementById('DI1').textContent; //load DI1
console.log(DI1_STATE); //DI1_STATE= ON or OFF(TYPEOF = String)
console.log(DI1_STATE=='ON'); //ALWAYS FLASE
console.log(DI1_STATE=='OFF'); //ALWAYS FLASE
var result = DI1_STATE.localeCompare('ON'); //WORK preset 1(TRUE) or -1(FLASE)
console.log(result);
if (DI1_STATE == 'ON'){
document.getElementById('DI1').style.backgroundColor = 'Coral';
document.getElementById('DI1').style.color = 'White';}
else{
document.getElementById('DI1').style.backgroundColor = '#ccc';
document.getElementById('DI1').style.color = 'black';}}
I wonder why == is not work
the whole Html code
I made the server at a microchip,i update the "DI1" by getsensorDATA3()
and the server command below

You always have to check for line breaks, spaces or other non visible characters when comparing string values from html elements. Try
var DI1_STATE =document.getElementById('DI1').textContent.trim()
localeCompare is used to determine sort order and only reports back if the reference string comes before or after the comparison string (in the sort order):
Negative when the referenceStr occurs before compareString
Positive when the referenceStr occurs after compareString
Returns 0 if they are equivalent
You might use it like array.sort((a, b) => b.localeCompare(a));
Tests....
let test = document.getElementsByTagName('textarea')[0].value;
console.log('"' + test + '"')
console.log('test == "TEST"', test == "TEST") // false
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 1
test = test.trim();
console.log('test == "TEST"', test == "TEST") // true
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 0
<textarea>TEST </textarea>

Related

REGEX to find a specific formula in a google sheet cell [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I have a google sheet addon, with custom formulas that fetch data from my API, I built a refresh mechanism to force the formulas to execute again to get updated data, but I want only specific formulas to refresh and not not every cell in the spreadsheet.
let's suppose my formula is called MYFORMULA(), I should only refresh if the cell contains this formula and it has 2 or less parameters, because the third one is always a date, which means it fetches historical data and doesn't need to be updated.
I need a function that given the cell content returns whether it should be refreshed or not:
some sample inputs and expected outputs:
=MYFORMULA(A1) --> true
=MYFORMULA(A1,B1) --> true
=MYFORMULA(A1,B1,C1) --> false
=TODAY() --> false
=ifs(C1=TODAY(),MYFORMULA(A1),A1<>"", MYFORMULA(A1,B1,C1),C1="","") --> true
=MYFORMULA(A1,B1,C1) - MYFORMULA(A2,B2) --> true
=if(D20="cc",if(B20<=MYFORMULA(A20),"Over","ok"),"-") --> true
So to sum up the input can be any kind of complex google sheet formula, but I only care if inside there is a call to MYFORMULA with less than 3 parameters
EDIT: this is what I have so far:
const MY_FORMULAS = ['MYFORMULA1', 'MYFORULA2'];
function shouldRefreshFormula(input) {
if(input[0] != '=')
return false;
var matches= input.split(/[\(,\)]/g).slice(0, -1);
const splittedArray = [];
while (matches.length > 0) {
var index = -1;
for (let formula of MY_FORMULAS) {
var formulaIndex = matches.indexOf(matches.find(e => e.includes(formula)), 1);
if (formulaIndex > -1) {
if (index == -1)
index = formulaIndex;
else if (formulaIndex < index) {
index = formulaIndex;
}
}
}
if(index > 0)
splittedArray.push(matches.splice(0,index));
else
splittedArray.push(matches.splice(0,matches.length));
}
for (let formula of splittedArray) {
if (formula.indexOf('') != -1)
formula.splice(formula.indexOf(''), formula.length);
if(input && formula.length > 0 && (MY_FORMULAS.some(x => formula[0].includes(x)))) {
if (formula.length < 4) {
return true;
}
}
}
return false;
}
what this function tries to do is to generate an array of arrays which contains the formula name plus its parameters so if I find a call to my formula I can validate the amount of parameters. This is not efficient plus I'm not sure I'm contemplating all combinations of inputs
MYFORMULA\(([^,\n]+,?){0,2}\)
MYFORMULA Literal MYFORMULA
Borders \( and \)
Group 1: ([^,\n]+,?)
[^,\n]+ One or more of: Not a comma or a newline
,? followed by a optional ,
{0,2} Group 1 repeated between 0 and 2 times
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const inputs = [
'=MYFORMULA(A1)  ',
'=MYFORMULA(A1,B1)',
'=MYFORMULA(A1,B1,C1)',
'=TODAY()',
'=ifs(C1=TODAY(),MYFORMULA(A1),A1<>"", MYFORMULA(A1,B1,C1),C1="","")',
'=MYFORMULA(A1,B1,C1) - MYFORMULA(A2,B2)',
'=if(D20="cc",if(B20<=MYFORMULA(A20),"Over","ok"),"-")',
];
console.table(inputs.map((s) => [s,/MYFORMULA\(([^,\n]+,?){0,2}\)/.test(s)]));
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Check out this one: MYFORMULA\(\w+?(,\w+)?\)|MYFORMULA\(\)
I think it will work provided you don't have nested functions as arguments
The regex above captures only MYFORMULA() | MYFORMULA(A1) | MYFORMULA(A1,B1)
This also requires the input to contain an equals sign
function shouldRefreshFormula(input) {
return input.match(/^=.*MYFORMULA\((\w+,?){0,2}\))/g) ? true:false;
}

trying to add numbers in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to write a program to decrypt a encrypted message. The encrypted message is a very long set of numbers ".296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304.
230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250.
282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333.
272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319.
246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245.....ect".
Each character of the message is transformed into three different numbers (eg.first character of message is '230 .280 .264' second character is '.327.301.265' ect).
so i am trying to use javascript to add the groups of three numbers and then save them as their own variable. thanks
Assuming msg has that string in it, this will split it up and add the triplets together.
const [, triplets] = msg
.split('.')
.slice(1)
.map(v => +v)
.reduce(([count, list], val, i) => {
if ((i + 1) % 3) return [count + val, list];
return [val, list.concat(count)];
}, [0, []]);
It would depend on how the data is transmitted. It looks like you could bring the data in as a string (or parse it into a string) and then use the split method to create an array of all of your numbers.
var numbers = "234.345.456.567"
var arr = numbers.split(".")
You would then loop over the array doing whatever you need for every set of three
var newArray[]
var i
for(i = 0; i < length; i += 3){
//Add values here
//Parse back to int
newArray.push("sum Value")
}
Hope this was along the lines of what you need.
Use a regular expression to match all groups of three, then map each group to the number by splitting the string by .s and adding the 3 together:
const input = '296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304. 230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250. 282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333. 272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319. 246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245';
const groupsOfThree = input.match(/\d{3}\.\d{3}\.\d{3}\./g);
const sums = groupsOfThree.map((group) => {
const nums = group.split('.').map(Number);
return nums[0] + nums[1] + nums[2];
});
console.log(sums);

How to check for two conditions using && operator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to use 1 If statement to check that both values are not zero
if ((minvalue !== 0) && (maxvalue !== 0)) {
// Both are not 0
}
else
{
// Both values are 0
}
I can get it to work by using two if statements
if ((minvalue !== 0){
if(maxvalue !== 0){
// Both values are not zero
}
}
But I'm not sure how to do it in one If.
This will also work
if (minvalue || maxvalue) {
// Both are not 0
}else {
// Both values are 0
}
Edit :
If you example doesn't work, you should consider doing
console.log(minvalue,maxvalue);
Your code works, so that's your minvalue and maxvalue which are wrong. Might be strings
Your first code block should be fine. If you want to get a bit more clever about it you could instead test that the product of both values is not zero (as anything multiplied by zero will be zero).
const minvalue = 1
const maxvalue = 3
if (minvalue * maxvalue !== 0) {
console.log('foo!') // foo!
} else {
console.log('bar...') // [not hit]
}
Also, stylistically, it's considered bad practice to leave hanging curly braces. Move your else and subsequent opening block curly brace up a line (as above).

Validating a phone number in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to be able to accept any way that a user inputs their phone number. I need help to include regular expressions that can validate the length of a number, bracket, hyphens and take care of spaces.
<script>
function Myfuc() {
var x = document.forms[0]["mobile"].value;
var z = document.forms[0]["mobile1"].value;
if(x == null || x == '')
{
alert("Field canot be empty");
return false;
}
if(x[0]!=0) // Starting with zero
{
alert("Mobile number should start with Zero");
return false;
}
var y=isNaN(x); // Checking numerals in first text box
if(y == true)
{
alert("Integers only accepted");
return false;
}
var z1=isNaN(z); // Checking numerals in first text box
if(z1 == true)
{
alert("Integers only accepted");
return false;
}
}
</script>
<form onsubmit="Myfuc()">
Mobile : <input type="text" id="mobile" name="mobile" style="width:40px;" maxlength=3> -
<input type="text" name="mobile1" maxlength=7>
<input type="submit" value="Click" name="sub" >
</form>
Everything you asked is here!!!, Spent 1 hr for this and imma beginner, dont worry code works well :-)
You could use this reg expression. I'm not too good with reg expressions but this could work in your case.
0\d{2}-\d{7}
/* start match with 0
check for 2 additional digits
check for hyphen
check for 7 additional digits after hyphen
*/
I also suck at creating regex expressions; however, you can always do something like this:
var str = document.getElementById('myInput').value,
numberOnly = str.replace(/-/g, ''),
errors = [], i;
if (isNaN(numberOnly)) {
errors.push('You must use numbers!');
} else if (str.split('-')[0].length !== 3 || str.split('-')[1] !== 7 || numberOnly > 10) {
errors.push('Invalid Format!');
} else {
console.log(numberOnly + ' is ok!');
}
if (errors) {
for (i = 0; i < errors.length; i++) {
console.log(i + '. ' + errors[i]);
}
}
It's simply testing each part of the string that is submitted.
First it checks to see (after we remove the hyphen) that the submitted value is actually a number.
Second, it splits the string in half to check if the start of the string has 3 characters, and then if the end of the string has 7 characters; lastly, it tests to see if the number is too large... etc, you can even check if its too small.
If you ever figure out a decent regex, you could instead use a switch statement to catch the errors (if any).
I think one might look like, [0-9]{3}(-)[0-9]{7} or something like that lol.
-
I've been working with PHP for awhile, so I forget if "length" returns a count, or the actual byte-size of a character, e.g. "é" is 2 bytes.
EDIT:
To check if the first character of the string is "0", you can always do:
if (str.length > 0 && str.charAt(0) != 0) { console.log('error'); }

numbers and words not numbers to words js [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple code gotten from the internet and it did not answer what I really wanted as output. I have two input fields; one for the input and another for the output and they are processed through this function:
<script type="text/javascript">
function AnEventHasOccurred() {
var x = document.getElementById("onkeyup").value
if (x >= "100") {
document.getElementById("eventlog").value = "" +
return x = ['Generalities'];
}
}
</script>
What I'm really needing is that when I enter numbers below 100, output must be Generalities. I haven't got it correctly. And I went here to ask some help. Thanks.
You're never outputting your value back into the output field. All you're doing is returning the value. You need to set the value of your output field to "Generalities".
Example
var input = document.getElementById("onkeyup").value;
// You should be giving your elements meaningful IDs.
if(+input < 100) {
document.getElementById("output").value = 'Generalities';
// Assumes an output field called "output".
}
Try this:
function AnEventHasOccurred() {
var x = document.getElementById("onkeyup").value;
if (x < 100){
document.getElementById("eventlog").value = "Generalities";
}
}
I see a few errors. Check this out for comparison:
function AnEventHasOccurred() {
// should probably save the elements to variables
// since you'll be checking and changing the values
var x = document.getElementById("onkeyup");
var y = document.getElementById("eventlog");
// should be 100, not "100"
if (x.value < 100) {
y.value = "Generalities";
} else {
y.value = "";
}
}
This should work fine. Check it out on jsfiddle.
More Recommendations
Your return statement doesn't correspond with your "output": it
does nothing valuable in this case.
You check or set the value of an input by getting the element and
using its value key.
You should put semi-colons at the end of most javascript lines, with the exceptions generally being curly brackets {}, comments // and /* */, and empty lines.

Categories