The great thing about JQuery is the way it makes accessing elements of the DOM extremely easy. Keeping with that, JQuery has some really nifty expressions built into it that means it even easier. For instance:

You have a form and in that form you have a pair of radio button named "makechoice" with the value 1 and 0. Now you want to hide a section of the form if they choose 0 and show the section if they choose 1. We've all done this before, you have to loop through the radio button array collection, see which radio button was checked, get the value of the checked radio button, determined whether you should hide the region based on the value retrieved and finally toggle the visibility of the region. Not too hard

You could probably do that in about 30 lines of code and 15 minutes to spare. With JQuery you can do this in 1 line of code. This is made possible using the wonderful expressions that JQuery has built into it. For example, to do the old show / hide based on a radio button selection (for readability I put the code on 3 lines…. sue me):

   $("input[name='makechoice']:checked").val() == 0 ? $("#HideMe").hide('slow') : $("#HideMe").show('slow');

The expression used to accomplish this is the "checked" expression. Basically all it does is limit the JQuery selection to the radio button that is checked. So now instead of looping over the radio button array to figure out which one was checked, I let JQuery do the work for me.

JQuery has many of these expressions built right into it. Some of the most often used ones are:

:visible – select the elements who display is set to visible
:hidden – select the elements who display is set to none
:enabled – select the elements that are enabled
:disabled – select the elements that are disabled

There are many more that I'm not going to get into. However if you want to explore them all, you can download the JQuery source and take a look.

Also in true JQuery fashion, here's how you can add your own.

Ref from: here

Add new comment