0

I got a question because I got stuck in checking the type of the object. I have the following situation:

<span class="checkbox">
  <input id="id1" type="checkbox" name="id1">
  <label for="id1"> check me</label>
</span>

<textarea cols="40" rows="10" id="id2" type="text" name="id2"></textarea>

I have a checkbox and a text area. Now I wrote some code which checks the object based on their type or tagname:

// TYPE
var type = $('#id1').attr('type');
$('.result').append("type: ", type);

// Type checking
if (type == "checkbox") {
    $('.test').append("[1] yes found one <br/>");
}
else{
    $('.test').append("[1] ahw I found an error");
}
// This will fail because case sensitive
if (type == "Checkbox") {
    $('.test').append("[2] yes found one");
}
else{
    $('.test').append("[2] ahw I found an error");
}

// TAGNAME
var tagname = $('#id2')[0].nodeName;
$('.result2').append("tagname: ", tagname);

// tagName checking
if (tagname == "TEXTAREA") {
    $('.test2').append("[1] yes found one <br/>");
}
else{
    $('.test2').append("[1] ahw I found an error");
}
// This will fail because case sensitive
if (tagname == "textarea") {
    $('.test2').append("[2] yes found one");
}
else{
    $('.test2').append("[2] ahw I found an error");
}

What I noticed is that for both objects, text area and checkbox, using the type and nodeName checking ends up in case sensitive problem. I can write multiple if statements that try to catch the desired case, e.g: Checkbox, CHECKBOX, checkbox etc.

So I was wondering what should be the best way to type check the object without knowing if it is case sensitive or having a pattern like for example this: CheCkBox?

Demo of my code can be found here: JSFIDDLE

Rotan075
  • 2,567
  • 5
  • 32
  • 54
  • 2
    Convert the values to the same case using either `toUpperCase()` or `toLowerCase()` – Rory McCrossan Sep 29 '16 at 13:06
  • @RoryMcCrossan same case? – Rotan075 Sep 29 '16 at 13:08
  • You should try **$('#myinput').is(':checkbox')** – Sumit Kumar Sep 29 '16 at 13:10
  • 1
    The answer to your actual question (*"what should be the best way to type check the object without knowing if it is case sensitive"*) is in the linked Q's answers. The reason you're seeing a difference is: `attr` faithfully reports the actual content of the attribute, so `type="checkbox"` will reliably give you `"checkbox"` and `type="CheckBox"` will reliably give you `"CheckBox"`. `nodeName` is different. In an HTML document, the nodeName of HTML elements is its `tagName`, which is [normalized to ALL CAPS](https://www.w3.org/TR/dom/#dom-element-tagname) regardless of how it is in the source. – T.J. Crowder Sep 29 '16 at 13:16
  • 2
    @sumitchoudhary: There's no need to fire up an entire selector engine just to check the type of an input. – T.J. Crowder Sep 29 '16 at 13:17

0 Answers0