1

In C#.Net, We would use Conditional Statement like this below:

string Place = TextBox1.Text == "" ? "School" : TextBox1.Text;

How to use Conditional Statement in JavaScript. I am assigning one value to the TextBox, If there is no value then I want to assign "1" to the TextBox.

Here I used like this,

document.getElementById('<%=txtPlace.ClientID %>').value   = obj[1];

If obj[1] == "" then I want to assign "1" to the TextBox. How to assign? It can be done easily by using If statement. But I want to know how to use Conditional Statement in JavaScript? Is there Conditional Statement in JavaScript? If so then how to use it?

4 Answers 4

5

Yes, Javascript does support the conditional operator:

document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] ? obj[1] : "1";

Alternatively, you can take advantage of its short-circuiting logical OR operator:

document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] || "1";
Sign up to request clarification or add additional context in comments.

6 Comments

@Hamidi: thank you for your answer. But I dont have idea about OR operator. Here if we use OR operator what value would be assigned to the TextBox.
@thevan, the two lines are equivalent.
@Daniel: Yes I tried. You are right. thank you so much Daniel.
@thevan, if obj[1] is the empty string, it will evaluate to false and the second operand will be evaluated and returned, so the value of the text box will be "1". If obj[1] is a non-empty string, it will evaluate to true, so the second operand won't be evaluated and the value of the text box will be the string stored in obj[1].
obj[1] || "1" means that if obj[1] is truthy -- i.e. anything but false, null, undefined, 0, "", NaN -- the OR statement will stop and return obj[1]. Otherwise, it will continue on to "1" and return that. The term short-circuit is used because once part of a || b || c || d evaluates to a truthy value, it stops and equals that value.
|
3

Yes, there is conditional statement in javascript, it works the same way:

document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] === "" ? "1" : obj[1];

Comments

1

The conditional (or ternary) operator is the same in JavaScript:

condition ? true-value : false-value

So your code would look like this:

document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] === "" ? "1" : obj[1];

Comments

1

Yes, there is and it behaves in the same way as in C#.

document.getElementById('<%=txtPlace.ClientID %>').value = obj[1]==""?"1":"something";

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.