If you have used jQuery before, then you are probably aware of the
val() function, which grabs the value of the selected tags. So, lets consider the following:
In order to get or modify the contents of either, you use the
val() method like so:
The use of the
val() method is pretty straight forward
and easy to understand. But, some form elements are a bit trickier.
Lets say you have a nice, plain ol' html select:
How would you get the selected element? After looking through the
documentation, the answer still might elude you. To do this, we are
taking advantage of the
:selected filter, which allows us to grab the, well selected option. Putting it all together we get:
It's simple enough, but it is not too obvious how to go about doing that. Something slightly more obscure is how to handle checkboxes. Let's say you have just a checkbox, and you want to find out if it is checked or not:
So, in order to find out if this is checked or not, the easiest way to go about doing it would be with a method called
is(). All this does is check the selected elements for specific filters. Luckily, there is a
:checked filter we can use, so testing the checkbox goes like so:
Then you can use this information however you want. T인용구his will give you an answer on whether the checkbox is checked or not. Slightly more complex are radio buttons, which come in groups. Lets take the follow set of radio buttons:
What we want here is to find which one of these is the currently
selected ones. To do this, we have to first get all of the radio
buttons in this group, so we use the name attribute. Then we use the
:selected filter like we did on the select. The whole ordeal will look something like so:
Since there is no real text inside the radio button, we have to use the
val() method. As long as we have a way to decode what that value means, we are in business.
These are some form selectors that I had to dig a little for, and they certainly are not that obvious unless you spend hours reading all the jQuery docs. Hopefully these will save you some digging of your own. Just remember, when you need coding help, just Switch On The Code.