Search code examples
jqueryformsdominputdetection

jQuery - how to form field type?


I have a situation where I need to extract a value from a form field, but I'm not sure what type it is (<input /> or <select />). Two questions:

  1. Is there a simple way to detect what type of input this is (name of tag or something)?
  2. Is there an API call that retrieves the value or selected option's value for either an input or a select (thus not making me find out which is what)?

var input = $('.form-field')[0];

// for <input> type tags

var value = $(input).val();

// for <select> tags

var value = $(input).find('option:selected').val();

Thanks.


Solution

  • var value = $('selector').val(); will work both with input and select.

    Edit: And about tag name, you can use something like this $('select')[0].tagName or $('select')[0].nodeName (as proposed in link in comments).