Reputation: 3769
I have the following:
var isChecked = $('#htmlEdit').is(":checked");
But I don't really need the variable isChecked and what I want to do is to assign a value to a variable called "action" so that if the test on the right above is true then
var action = "Editing HTML"
if not then
var action = "Editing"
Is there a clean way to do this without just using an if-else?
Upvotes: 1
Views: 145
Reputation: 54387
var result = someCondition == true ? "state 1" : "state 2";
// the first operand must evaluate to a boolean
var result = someCondition ? "state 1" : "state 2"; // shortened
var result = a == b ? "state 1" : "state 2"; // arbitrary condition
This is the ternary operator and behaves the same in JavaScript as most/all c-style languages.
Upvotes: 2
Reputation: 30676
Yes there is:
var action = $('#htmlEdit').is(":checked") ? "Editing HTML" : "Editing";
Upvotes: 7
Reputation: 100
Yes you can use conditional operator:
var variableToBeAssigned = conditiontoBechecked ? valueTobeAssignedONSucessOfCondition : valueToBeassignedONFailureOfCondition;
In your case, you can just use:
var action = $('#htmlEdit').is(':checked') ? 'Editing HTML' : 'Editing';
Upvotes: 0
Reputation: 6499
?
is also called as ternary operator
.
This is more of a language construct, rather than a Framework stuff.
C#
is a language
and Jquery
is a framework
build on Javascript
(a language).
And Javascript
language and most of the languages (C, C++, C#, Java, Javascript
) support this operator.
Upvotes: 0
Reputation: 1503090
Yes, Javascript has a conditional operator. You should be able to write:
var action = $('#htmlEdit').is(":checked") ? "Editing HTML" : "Editing";
(Did you try this before asking the question?)
Upvotes: 3