views:

58

answers:

2

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;
}

}
+5  A: 

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...

Nick Craver
This didn't seem to work, and made it stop working in Firefox too. Does this need to be placed after the function is called or at the start of the script?
David
@David: It needs to be declared before it is called.
CD Sanchez
+1  A: 

If you are already using jQuery in your project you can use $.inArray()

http://api.jquery.com/jQuery.inArray/

jhanifen