1

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.

sa125
  • 28,121
  • 38
  • 111
  • 153
  • 3
    `$(input).val()` will work nicely for `select` – Igor Dymov Sep 15 '11 at 11:38
  • 1
    Are you looking for something like this? http://stackoverflow.com/questions/1532331/can-jquery-provide-the-tag-name – peirix Sep 15 '11 at 11:39
  • @Igor Dymov - how did I miss that?.. :) Last time I tried that was a while back - is it a recent change to jQuery? O'well - works. Thanks. – sa125 Sep 15 '11 at 11:43

2 Answers2

1

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).

Beniamin
  • 3,198
  • 2
  • 19
  • 17
0

you can do in this way:

$(':input').val();
oezi
  • 51,017
  • 10
  • 98
  • 115
Vivek
  • 10,978
  • 14
  • 48
  • 66