I want to do something like
if(something.val() == 'string1')
{
something.val('string2');
}
else if(something.val() == 'string2')
{
something.val('string1')
}
But in one line of code. I can't quite remember how it's done, but it involves question marks and colons...
Try:
something.val(something.val() == 'string1' ? 'string2' : 'string1');
It is called a ternary expression.
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.
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()]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With