Posted By: Anonymous
I have a page where the input type always varies, and I need to get the values depending on the input type. So if the type is a radio, I need to get which is checked, and if it is a checkbox I need to now which are checked, and if it is a drop down I need to know which is selected, and I if it is a text/textarea I need to know the values.
Any idea on how to do that?
EDIT Feb 1, 2013. Due to the popularity of this answer and the changes to jQuery in version 1.9 (and 2.0) regarding properties and attributes, I added some notes and a fiddle to see how it works when accessing properties/attributes on input, buttons and some selects. The fiddle here: http://jsfiddle.net/pVBU8/1/
get all the inputs:
var allInputs = $(":input");
get all the inputs type:
get the values:
NOTE: .val() is NOT the same as :checked for those types where that is relevent.
EDIT Feb 1, 2013 – re: jQuery 1.9 use prop() not attr() as attr will not return proper values for properties that have changed.
to get the value of the check – whatever it is currently. or simply use the ‘:checked’ if you want only those that ARE checked.
EDIT: Here is another way to get type:
Note that the form of:
is perferred over
which both equate to:
but the “input” is desired so it only gets the inputs and does not use the universal ‘*” when the form of
$(':radio') is used which equates to
EDIT Aug 19, 2015: preference for the
$('input[type=radio]'); should be used as that then allows modern browsers to optimize the search for a radio input.
EDIT Feb 1, 2013 per comment re: select elements
will return either “select-one” or “select-multiple” depending upon the “multiple” attribute and
returns the same for the first select if it exists. and
will return the type if it exists or “howdy” if it does not.
returns the property of the first one in the DOM if it exists or “undefined” if none exist.
returns the type of the first one if it exists or an error if none exist.