Fun-fun-FUNctions...with IE8

We developers love to gripe - about client special requests, internet speed, cold coffee...you name it - but we always seem to gripe about whatever tech restrictions working at the time. This holds true when programming HTML (or HTML5, if you're lucky) for various browsers - and seems especially true when dealing with versions of Microsoft Internet Explorer that are older than whatever-the-current-iteration-is.

With that conversational stage set, enter: IE8. Instead of griping, let's talk about a simple workaround to make some JavaScript work in IE8.

Let's say you want to create a function that evaluates whether a checkbox has been selected ('checked' or 'ticked') or not. First, lay in the checkbox HTML code in between the <body> tags:


<input type="checkbox" name="Quiz1" id="Quiz1a" value="1"  />



Easy enough. No 'submit' button or 'form' is needed, as we will only be evaluating the checkbox's activity. Now, let's add a simple function that gives an alert if the checkbox is selected:


function myFun() {
    if (Quiz1a.checked == true) {
        alert('The checkmark has been selected.');
    } else {
        alert('Nothing selected');
    }
}



While this works in browsers like Chrome, Safari,...even IE9 or IE10, it may not function as well or at all in IE8 (see notes below).

Why? Without getting into the different JS Engines - and debating their worth - 'under the hood' of each iteration of IE, just know that the way IE8 handles JavaScript is very different than the way it handles JS in later versions. Weirdly, the code above may work on your browser, as-is (*maybe!) depending on which updates your particular version of IE8 has.

I've found this IE8/JS issue is especially true when evaluating an entire (HTML) page full of checkboxes and the issue seems further complicated function with many different loops being tested (if...else if...else, switch case, etc.), using the checkmarks. Thus, to get the above function to work effectively, it is better to be very specific about what we are evaluating. To do so, we need to invoke JavaScript's 'getElementById' element:


function myFun() {
    if (document.getElementById('Quiz1a').checked == true) {
        alert('The checkmark has been selected.');
    } else {
        alert('Nothing selected');
    }
}



Now the code will work in IE8, with only a little extra work. So, without saying one browser is better than another (...because it IS...lol), save yourself some time and (potentially) grief by creating clean and specific code, so that your projects can work no matter what browser they land on. Good luck! :)

Comments