0

I have an array with different elements inside it. Like array contain input elements and select elements. I want to check for particular type. I tried this but it didn't work

var mandotaryElementsArray = $('.mandotary');

$.each(mandotaryElementsArray, function(index, element){

    if (element == input) {

        var $inputElement = $(this);
        var test1;

    } else if (element == select) {

        var $selectElement = $(this);
        var test2;

    }

}); //end of .each()

Actually i want to check something that is similar to instance of in Java. Here i want to check if element is type of input then do this, if element is type of select then do this, if element is type of radiobutton then do this.. How can i make this check here? Thanks

Basit
  • 8,426
  • 46
  • 116
  • 196

2 Answers2

7

You can use either the .tagName property (which always returns uppercase for HTML):

$('.mandotary').each(function(index, element) {
    if (element.tagName == "INPUT") {
        // code here
    } else if (element.tagName == "SELECT") {
        // code here
    }
});

Or, you can use jQuery's .is():

$('.mandotary').each(function(index, element) {
    var $element = $(element);
    if ($element.is('input')) {
        // code here
    } else if ($element.is('select')) {
        // code here
    }
});

Even better would probably be to let the selector do all the work for you and just select the items you want for a particular operation and operate on the desired selector like this:

$('input.mandotary').hide();
$('select.mandotary').show();
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Just use .is() to match the tag name:

if (element.is('input'))

But ideally rework the code and don't check for tag names in your loop.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • Hi, thanks, Actually in my page there are several elements whom i want to check. Like textField, that i want to check for null, select elements that i want to check if a particular value is selected, check box that i want to check, whether tick or not and so on. So what i did i gave them each a class **mandotary** and got then in array. As i did above. Now if in array i have text field that is input element, then i check for null, if it is select then i can check for value and so on. Now can you tell me how can i better do this thing. As you said **ideally rework the code:)** Thanks – Basit Feb 08 '12 at 06:13