Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery split() and indexOf results in "Object doesn't support this property or method"

I have the following code:

var selected = $('#hiddenField').val().split(",");
...
if (selected.indexOf(id) > 0) {
   ... set value ...
}

I'm dynamically creating a CheckBoxList, and trying to remember the state of the checkboxes by putting the selected IDs into the hidden field.

I get an error stating that "Object doesn't support this property or method". My assumption is that selected is an array, which should support indexOf. Is that incorrect?

like image 461
chris Avatar asked Apr 09 '10 15:04

chris


2 Answers

There's an jQuery method to overcome the lack of indexOf(), you can use .inArray() instead:

var selected = $('#hiddenField').val().split(",");
if ($.inArray(id, selected) > -1) {
   ... set value ...
}

jQuery.inArray() exists for just this reason...if you're including jQuery already, no need to write the function again. Note: This actually returns a number, like indexOf() would.

like image 172
Nick Craver Avatar answered Oct 02 '22 18:10

Nick Craver


Based on your error message, I'm assuming this is coming from Internet Explorer.

Surprise! Internet Explorer (including version 8) does not support indexOf for arrays.

Here is Firefox's implementation you can use:

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;
  };
}
like image 34
Matt Avatar answered Oct 02 '22 19:10

Matt