How to tips and tricks for Microsoft Visual Studio .net

Tuesday, November 3, 2015

IIf in javascript/jQuery


The conditional operator(c#/java/javascript) or IIf(vb), also called an inline if statement, is very useful.

I have used IIF in my vb and c# exploits very often. I wrote a post about the conditional operator for c# here, and it has proven to be very popular.

To use the conditional operator in javasctipt or jQuery is just as simple as using it in c# or vb.

The syntax is: (condition ? first_expression : second_expression);

A simple example is to set a variable based on the condition of another variable:

      var animal = 'cat';
      var species = (animal == 'cat' ? 'feline' : 'canine');

This snippet checks the variable animal to see if it is set to 'cat'. If the condition is true, species is set to 'feline'. If not, species is set to 'canine'.

Another way to use it would be to set the class of a web page element using the jQuery addClass method:

($("#contactnumber").hasClass("requiredElement") ? "" : $("#contactnumber").addClass("requiredElement"));

This snippet checks the element with an id of contactnumber to see if it has the class requiredElement assigned to it. If it does, then nothing is changed, otherwise the class requiredElement is added to the element.

Please let me know in the comments, if this helped.


Happy coding.

3 comments:

  1. Thanks for helping me to get this done:
    var middle = (ContactInfoMiddleName == null ? '' : ContactInfoMiddleName + ' ');
    $('#<%=txtName.ClientID %>').val(ContactInfoFirstName + ' ' + middle + ContactInfoLastName);

    ReplyDelete