Now that I am working a lot more with jQuery I thought I would start posting little examples of why I enjoy using it so much. If you are looking for a full on beginner or selective tutorial you should head over to the tutorials section on the jQuery site, it is packed with great stuff. This first example is a short one but to me is the main reason I have been using jQuery so much lately. Just keep in mind when I am going through these examples that I am no JS expert so there may be better ways to accomplish the task at hand.
Everyone has dealt with a select box (drop down) at one point or another right? One thing I really hate about JS is how much code I have to write just to accomplish what should be a simple task. Here is the way I would of done it in the past. In our example we have a list of developers in a select menu. We explicitly set an onChange event handler (not a good practice more on that another time) that calls our onSelectChange method. The problem now is that you have to grab the element from the dom, find the selected index and write all this code to get the values and text. I just don't have fun writing this and you can probably see why. If there is a better way that is my fault and while this would work its just no fun for me.
Now on to the fun part. The first thing we need to do is include the jquery library and create a ready function. We also have our list of developers and our goal is to write out what developer the user selects every time the selection changes.
The first thing we need to do is to notify our application that the user changed their selection. To do that we can use a jquery change event. To use this event we must first have a jquery object. This is really where the beauty of the code lies, almost everything is returned as a jQuery object. By selecting our developer select we simply attach an event and pass in the name of the function we would like to call when the event occurs.
Now we can write our method that handles the actual logic of our application. Remember all that code we wrote earlier, it was ugly right? This to me is a better approach, first you can get the selected option using the option:selected selector. This will return to us a jQuery object and we can get what we need by using the val() and text() attributes. The html() method in this case sets the contents of an element.
There is a link below for a live demo of this. This was just a quick example of why I enjoy using jQuery. The code is clean and I am never guessing what some method returned to me (object/string/date) because I will almost always get back a jQuery object. If you have any questions about this example let me know and for you more advanced users I got some good stuff in the pipe so stay tuned.