Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is indexOf not working in Internet Explorer?

This function executes during the forms onSubmit, and works fine in Firefox and Chrome, but not in IE. I suspect it's indexOf, but I cannot seem to find a way to get it to work.

function checkSuburbMatch(e) {

var theSuburb = document.getElementById('suburb').value;
var thePostcode = document.getElementById('postcode').value;

var arrayNeedle = theSuburb + " (" + thePostcode + ")";

if(suburbs.indexOf(arrayNeedle) != -1) {
    alert("Suburb and Postcode match!");
    return false;
} else {
    alert("Suburb and Postcode do not match!");
    return false;
}

}
like image 488
David Avatar asked Sep 13 '10 02:09

David


People also ask

Does IndexOf work on arrays?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

Does IndexOf work on IE?

This function executes during the forms onSubmit, and works fine in Firefox and Chrome, but not in IE.

What is the function of the IndexOf () in arrays?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

IE simply doesn't have this method on Array, you can add it yourself though, from MDC:

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 adds .indexOf() if it's missing (at this point that means you're in IE<9) then you can use it. As for why even IE8 doesn't have this already? I can't help you there...

like image 148
Nick Craver Avatar answered Oct 21 '22 12:10

Nick Craver