1

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?

1
  • 1
    Did you try the C# conditional syntax in JavaScript? Commented Mar 3, 2012 at 9:32

6 Answers 6

7

Yes there is:

var action = $('#htmlEdit').is(":checked") ? "Editing HTML" : "Editing";

Conditional operator on MDN

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. I didn't realize I could do the same as C#.
Glad it helped. I have added a link for documentation. You could also check the list of Expressions and Operators.
3

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?)

Comments

2
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.

Comments

1

var action = isChecked ? "Editing HTML" : "Editing";

1 Comment

OP says that he doesn't really need the var isChecked.
0

? 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.

Comments

0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.