views:

110

answers:

1

The below function works fine on opera, firefox and chrome. However in IE8 it fails on if ( allowed.indexOf(ext[1]) == -1) part.

Does anyone know why? Is there any obvious mistake?

function CheckMe() {
    var allowed = new Array('docx','xls','xlsx', 'mp3', 'mp4', '3gp', 'sis', 'sisx', 'mp3', 'wav', 'mid', 'amr', 'jpg', 'gif', 'png', 'jpeg', 'txt', 'pdf', 'doc', 'rtf', 'thm', 'rar', 'zip', 'htm', 'html', 'css', 'swf', 'jar', 'nth', 'aac', 'cab', 'wgz');
    var fileinput=document.getElementById('f');
    var ext = fileinput.value.toLowerCase().split('.');
    if ( allowed.indexOf(ext[1]) == -1) 
    {
        document.getElementById('uploadsec').innerHTML = document.getElementById('uploadsec').innerHTML;
        alert('This file type is not allowed!');
    }
}
+4  A: 

IE<9 doesn't have an .indexOf() function for Array, to define the exact spec version, run this before trying to use it:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

This is the version from MDC, used in Firefox/SpiderMonkey. In other cases such as IE, it'll add .indexOf() in the case it's missing...basically IE8 or below at this point.

Nick Craver
You might want to mention this being adapted from MDC: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
Tim Down
@Tim - That's where the links are to :) I'll make this a bit clearer in the answer though *Edit:* updated, hopefully much clearer source citing now.
Nick Craver
Ah OK, I didn't spot the links.
Tim Down