JQuery - determine if an input element is a text field or select a list

How can I tell if an item returned by an input filter is jQuery, a text box, or a list?

I want to have a different behavior for each (text field returns text value, select returns both keys and text)

Setting example:

<div id="InputBody"> <div class="box"> <span id="StartDate"> <input type="text" id="control1"> </span> <span id="Result"> <input type="text" id="control2"> </span> <span id="SelectList"> <select> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> </span> </div> <div class="box"> <span id="StartDate"> <input type="text" id="control1"> </span> <span id="Result"> <input type="text" id="control2"> </span> <span id="SelectList"> <select> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> </span> </div> 

and then script:

 $('#InputBody') // find all div containers with class = "box" .find('.box') .each(function () { console.log("child: " + this.id); // find all spans within the div who have an id attribute set (represents controls we want to capture) $(this).find('span[id]') .each(function () { console.log("span: " + this.id); var ctrl = $(this).find(':input:visible:first'); console.log(this.id + " = " + ctrl.val()); console.log(this.id + " SelectedText = " + ctrl.find(':selected').text()); }); 
+71
jquery jquery-selectors
Feb 24 '11 at 17:36
source share
2 answers

You can do it:

 if( ctrl[0].nodeName.toLowerCase() === 'input' ) { // it was an input } 

or is it that is slower but shorter and cleaner:

 if( ctrl.is('input') ) { // it was an input } 



If you want to be more specific, you can check the type:

 if( ctrl.is('input:text') ) { // it was an input } 
+132
Feb 24 '11 at 17:38
source share

alternatively you can get DOM properties with .prop

here is an example code for the select block

 if( ctrl.prop('type') == 'select-one' ) { // for single select } if( ctrl.prop('type') == 'select-multiple' ) { // for multi select } 

for text box

  if( ctrl.prop('type') == 'text' ) { // for text box } 
+23
Jun 16 '13 at 10:55 on
source share



All Articles