Any way to toggle between two strings using one piece of JavaScript?

Solution 1:

Try:

something.val(something.val() == 'string1' ? 'string2' : 'string1');

It is called a ternary expression.

Solution 2:

Look ma, no ternary operator!

The following works because Javascript short circuits boolean expressions.

If something == string1 then evaluate string2 -- since string2 is a truthy value and the next expression involves the OR operation there is no need to continue. Stop and return string2.

If something !== string1 then it will skip the next operand because if it is false, there is no point in evaluating the next operand (with AND). It will "jump" to the OR operation and return string1.

function toggleString(something, string1, string2) {
   return something == string1 && string2 || string1;
}

something.val(toggleString(something.val(), "string1", "string2"));

If you want the assignment done:

function toggleValue(something, string1, string2) {
   something.val(something.val() == string1 && string2 || string1);
}

toggleValue(something, "string1", "string2"); // something is a jQuery collection

In the end however, I would end up using the ternary operator because this solution might be unclear to other programmers. If you come from Java or other languages, you may expect the function to return a boolean because of all the boolean operators.

Solution 3:

Another way to do it using object properties:

{ 'string1': 'string2', 'string2': 'string1' }[value]

As in the question:

something.val(
  { 'string1': 'string2', 'string2': 'string1' }[something.val()]
)

Solution 4:

How about using @Daniel's code along with a jquery function:

$.fn.toggleVal = function (str1, str2) {
     return this.val(this.val() == str1 && str2 || str1);
};
$("input").toggleVal('string 1', 'string 2');