-1

Is there an 'or' operator for an if statement? I want to change the value of a text field depending on the content of another. If the value is "Your Company" OR (in german) "Ihr Unternehmen", it's supposed to leave the #cmp field blank. Otherwise it should take over the value. I can't get it working with an or operator (second code block), nor with an else if statement.

// Working for one string:
if ($("#listencmp").val() != "Ihr Unternehmen") {
     var comp = $("#listencmp").val();
     $("#cmp").val(comp);
 } else {
    $("#cmp").val("");
 }

// Not working for two strings:
if ($("#listencmp").val() != "Ihr Unternehmen" || "Your Company") {
     var comp = $("#listencmp").val();
     $("#cmp").val(comp);
 } else {
    $("#cmp").val("");
 }
fabe
  • 15
  • 4

6 Answers6

2

Think about the or operator. You are OR'ing a Boolean expression and a String. You need to build a second Boolean expression.

if ($("#listencmp").val() != "Ihr Unternehmen" || $("#listencmp").val() == "Your Company")
struthersneil
  • 2,700
  • 10
  • 11
1
var listencmp = $("#listencmp").val();
if ( listencmp == "Ihr Unternehmen" || listencmp  == "Your Company") {
 $("#cmp").val("");
}
else{
 var comp = $("#listencmp").val();
 $("#cmp").val(comp);
}

side note: it's better to use strict equality (replace == with === )

Amine Hajyoussef
  • 4,381
  • 3
  • 22
  • 26
0

Use this:

if ($("#listencmp").val() != "Ihr Unternehmen" || 
     $('#listencmp').val() != "Your Company") {
   // do the stuff here, this will work fine!
}

You need to complete the conditions then move on the next one. And the next ones needs to have two conditions to compare on.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
0

You have to use the compare statement to the second condition too:

if ($("#listencmp").val() !== "Ihr Unternehmen" || $("#listencmp").val() === "Your Company") {
  // your code here
}

Probably would be a more recommended to use strict equality operator (===).

Endre Simo
  • 11,330
  • 2
  • 40
  • 49
0

You should be using the OR operator to check if your val() === both values. If you stick to exclusion, go for the && operator instead.

Sylvain
  • 158
  • 1
  • 9
0

I would like to add that this can be a good use of the ternary operator, achieved in one line of code.

HTML:

<input type="text" id="cmp"/>
<input type="text" id="listencmp" value="Your Company"/>

Javascript:

$("#cmp").val(($("#listencmp").val() === "Your Company" || $("#listencmp").val() === "Ihr Unternehmen")?"":$("#listencmp").val());
itsmikem
  • 2,118
  • 2
  • 26
  • 31