Over the past few years, the advent of Ajax has played a major part in allowing our web applications feel a bit more like what we’re used to running on the desktop.
Without the ability to asynchronously submit requests, we’d still be stuck with having to reload an entire page every time we submit information.
Although the rise of various JavaScript frameworks have made it much easier to manage the nuances of Ajax across the major browsers, there are still a few problems that we have to deal with if we want to build robust experiences that scale across multiple versions of our browsers.
Case in point: I was recently working on a project that used multiple hidden input fields in order to submit data to the server. It performed flawlessly in all browsers except IE7.
Here’s how you can populate hidden input fields in all browsers with a combination of jQuery and vanilla JavaScript…
The Base Case
The primary action that I was attempting to achieve was to set the URL of a specific anchor as the value of an input box.
Assuming that I had an input field with an ID of “myURL” and that I have an event handler attached to an anchor, the code looked like this:
$('input#myURL').attr('value', $(this).attr('href'));
Simple jQuery-based code, right? Unfortunately, Internet Explorer 7 didn’t like this.
What’s The Problem?
After doing some basic debugging, I found that the problem was surrounding the use of the attr() function. Specifically, IE7 didn’t appear to support a property or method used by jQuery for setting that specified attribute.
As such, I had to mix vanilla JavaScript with a little bit of jQuery. Of course, the basic functionality still remained: Set the value of an input box equal to that of the anchor’s URL:
var oInput = document.getElementById('myURL');
oInput.value = $(this).attr('href');
This took care of it.
Final Implementation
Personally, when I have to fallback to fixes like this, I like to make sure that I target only the specific browser that needs the code written this way. In the future, it makes it easy to know why I wrote code a specific way and it makes it easy to remove a block of code should we opt to stop supporting an older browser.
Since I wanted to apply the fix specifically to IE7, I used jQuery’s built-in browser property and I parsed the version of the browser in order to specifically target 7.0:
if($.browser.msie && parseFloat($.browser.version) === 7.0) {
var oInput = document.getElementById('myURL');
oInput.value = $(this).attr('href');
} else {
$('input#myURL').attr('value', $(this).attr('href'));
}
Despite the fact that this was a relatively painless fix, I couldn’t help but wonder if IE7 is already becoming the new IE6. Yikes.
Speak your mind...