jeudi 29 septembre 2016

Type checking case sensitive [duplicate]

This question already has an answer here:

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




Aucun commentaire:

Enregistrer un commentaire