If else statement is not working correctly - javascript

In this function the user selects a value in the dropdown menu and whatever value is selected, it would change var B to its corresponding value.
function test(){
var A = ["", "A", "B", "C"];
var B = document.getElementById("myfile");
if(A.value = "A"){
B.selectedIndex = [2];
}
else if(A.value = "B"){
B.selectedIndex = [4];
}
else if(A.value = "C"){
B.selectedIndex = [1];
}
}
The problem I am having is that every time I select B or C, it always defaults to index [2] and not [4] or [1].

You're assigning when you mean to compare. Use ==, not =, for comparison.
if(A.value == "A"){
B.selectedIndex = [2];
}
else if(A.value == "B"){
B.selectedIndex = [4];
}
else if(A.value == "C"){
B.selectedIndex = [1];
}

= is assignment
== is test for equality for content
=== is test for equality for content and data type
In your case, = is certainly a typo. I'd recommend using === for maximum program stability.
Some folk tend to write "A" == A.value so a misplaced assignment gives you a syntax error.

You're assigning the value in your ifs not testing it. This will return the value that is assigned. The if condition will be true unless the following values are assigned and therefore returned, false, 0, an empty string, null, undefined or NaN. That's why you are entering the block of the first if statement.
Change the single equals to double or triple equals.
if(A.value == "A"){
B.selectedIndex = [2];
}
else if(A.value == "B"){
B.selectedIndex = [4];
}
else if(A.value == "C"){
B.selectedIndex = [1];
}

Use == not =
Your statement checks if its possible to set the value.(Every time...)

Related

JavaScript not comparing properly

I have a program written in JS. It compares output of an function with number 4. However, it seems it cannot compare properly.
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
//OUTPUT IS NULL, WHICH IDEALLY SHOULD BE "Value1"
Can any one guide me where am I making mistake?
You are trapped in the same mistake which most JS developers do!
There is an difference between === and == in JS. (Difference between == and === in JavaScript). Because of this, when you compare "4" with 4, it compares (String 4) with (Numeric 4), hence returning your else condition.
Solution: Just replace === with ==
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate == 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
https://jsfiddle.net/pfrvn485/
It depends, if you want to check if notValidate is a string:
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === "4") // Change here
{
console.log("Value1");
}
else
{
console.log("null");
}
if you want to check if notValidate is a number, use parseInt():
var myStringNotValidated = "3T-4T";
var notValidate = parseInt(myStringNotValidated.substring(3, 4)); // Change here
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
Your if condition is wrong if(notValidate === 4) checks 4 as string. either you can use if(notValidate=='4') or convert it to number & check.
This is because === compares both value and type. In your program, noValidate contains a value of 4 but its type is string and you are comparing it with 4 whose type is number.
You can either use == or typecast noValidate to number.
var myStringNotValidated = "3T-4T";
var notValidate = Number(myStringNotValidated.substring(3, 4));
console.log(typeof notValidate);
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
You're comparing the string("4") with the int type(4). Need to be converted to an integer before comparing.
var myStringNotValidated = "3T-4T";
var notValidate = parseInt(myStringNotValidated.substring(3, 4));
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
Try this :
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === "4")
{
console.log("Value1");
}
else
{
console.log("null");
}

How to compare values in JavaScript?

How do I compare values in JavaScript?
My code below should alert "2" but it does not work.
var test_val = "TWO";
if(test_val = "ONE")
{
alert("1");
}
else if(test_val = "TWO")
{
alert("2");
}
You have to use comparison operators (==, ===, !=, !==). The == and != are type insensitive and performs an implicit cast on the second operand. The === and !== operands are performing type sensitive comparison that includes type checking.
var test_val = "TWO";
if(test_val === "ONE")
{
alert("1");
}
else if(test_val === "TWO")
{
alert("2");
}
Type Sensitive
//1 === "1" false
//1 === 1 true
//1 !== "1" true
//1 !== 1 false
Type Insensitive
//1 == "1" true
//1 == 1 true
//1 == 2 false
//1 == "2" false
A single = is assignment (Used for setting values)
A double == is used for comparing and will return true/false.
A triple === is used to compare value and type. will return true/false only if the values and types match.
The best ANSWER to this is that whenever you do comparison you CANNOT use = inside the parenthesis. You can use either == or === depending on what you want to compare. Here's what you can do:
var test_val = "TWO";
if(test_val == "ONE")
{
alert("1");
}
else if(test_val == "TWO")
{
alert("2");
}
= is Assignment operator.
use == Relational Operator.
Reference:
http://www.tutorialspoint.com/java/java_basic_operators.htm

Removing numeric values from alphanumeric string

I want to remove all numeric values from a string
But only if the string contains at least one letter.
How can I do this in JavaScript?
For e.g.
var s = "asd23asd"
Then result must be asdasd
However if
var s = "123123"
Then result must be 123123 as the string does not have any letters.
function filter(string){
var result = string.replace(/\d/g,'')
return result || string;
}
or directly
var newString = string.replace(/\d/g,'') || string;
Why || works
the || and & are conditionals operators and sure that you used in if, while ...
If you do somethin like
var c1 = false, c2 = true, c3= false, c4 = true;
if( c1 || c2 || c3 || c4) {
}
This evaluation will stop in the first moment that is valid or invalid.
this mind that the evaluation stop in c2 this mind that is more fast
(true || false) than (false || true)
At this point we can add another concept, the operator return always the last element in the evaluation
(false || 'hey' || true) return 'hey', remember in JS 'hey' is true but '' is false
Interesting examples:
var example = {
'value' : {
'sub_value' : 4
}
}
var test = example && example.value && example.value.sub_value;
console.log(test) //4
var test_2 = example && example.no_exist && example.no_exist.sub_value;
console.log(test_2) //undefined
var test_3 = example.valno_existue.sub_value; //exception
function test_function(value){
value = value || 4; //you can expecify default values
}
You can try this. First check if the word contains any alphabet, if yes then replace.
var s = "asd23asd";
if(/\w+/.test(s))
s = s.replace(/\d+/g, '');
([a-zA-Z]+)\d+|\d+(?=[a-zA-Z]+)
You can try this.Replace by $1.See demo.
https://regex101.com/r/nS2lT4/27
Javascript Code
var txt='asd23ASd3';
if(parseInt(txt))
var parsed=txt;
else
var parsed=txt.replace ( /[^a-zA-Z]/g, '');
console.log(parsed)

Alternative to multiple or statements in an if block in Javascript

I have to check for
if(x == "An" || x == "Apple" || x == "A" || x == "Day" || x == "Keeps" || x == "The"....and so on){
return true;
}
else{
return false;
}
Is there a better way to write the if statement for large number of || conditions?
You could store the values in an array and then check to see if x is in the array of values using .indexOf():
Example Here
var values = ["An", "Apple", "A", "Day"];
if (values.indexOf(x) !== -1) {
return true;
} else {
return false;
}
matches = ["An", "Apple", "A", "Day"];
if (matches.indexOf(x) > -1){
return true;
} else{
return false;
}
don't do if x then true else false do simply return x. so:
var values = [...];
return values.indexOf(x) > -1;
I am no Java coder, so there may be syntactical errors, but I used the concept of what I would do in VB and then applied the syntax I found using uncle Google.
string[] SearchTerm = { "An", "Apple", "A","Day","Keeps","The" }
for(String str : SearchTerm){
if(x==SearchTerm[i]){
return true;
break;
}
else{
return false;
}
}

Javascript - Can there be 3 or more '===' in a single statement?

So, for example, will
function myFunction() {
if(var_1 === var_2 === var_3 === var_4) {
return true;
} else {
return false;
}
}
return true or false when
var_1 = true;
var_2 = true;
var_3 = true;
var_4 = true;
Also, what will the function 'myFunction' return when
var_1 = false;
var_2 = false;
var_3 = false;
var_4 = false;
and
var_1 = "abc";
var_2 = "abc";
var_3 = "abc";
var_4 = "abc";
Thanks a lot!
No, because the first === will equate to true (or false) and will not equal the next variable.
So var_1 === var_2 will either be true or false.
It then compares that result to var_3 like this true/false === var_3. That gives a result of true or false. That second result is then compared to var_4.
So this will be true according to your test:
var_1 = "yes";
var_2 = "apple";
var_3 = "amazing";
var_4 = false;
I presume that's not what you want :)
The case with three variables will be easier to work with. It'll be interpreted as:
(a == b) == c
Which will be:
(some boolean) == c
That's probably not what you intend to happen. To work around this, use the transitivity of equality:
(a == b) && (b == c)
In all 3 condition the function will return true..
yes there can be 3 '===' in a single statement

Categories