Gilberto Albino
Gilberto Albino

Reputation: 2745

Javascript push() method not working aside jQuery inArray()

I am trying to add values to a simple array, but I can't get the values pushed into the array.

So far so good, this is the code I have:

codeList = [];

jQuery('a').live(
    'click', 
    function()
    {
         var code = jQuery(this).attr('id');
         if( !jQuery.inArray( code, codeList ) ) {
              codeList.push( code );
              // some specific operation in the application
         }   
    }
);

The above code doesn't work! But if I manually pass the value:

codeList = [];

jQuery('a').live(
    'click', 
    function()
    {
         var code = '123456-001'; // CHANGES HERE
         if( !jQuery.inArray( code, codeList ) ) {
              codeList.push( code );
              // some specific operation in the application
         }   
    }
);

It works!

I can't figure out what's going on here, because if I do other tests manually it also work!

Upvotes: 3

Views: 1942

Answers (2)

Fabrício Matté
Fabrício Matté

Reputation: 70159

jQuery.inArray returns -1 when the value is not found, also .live is deprecated on jQuery 1.7+ and you're missing a var statement in your codeList declaration. Here's a rewrite of your code:

//without `var`, codeList becomes a property of the window object
var codeList = [];

//attach the handler to a closer ancestor preferably
$(document).on('click', 'a', function() {
    //no need for attributes if your ID is valid, use the element's property
    var code = this.id;
    if ($.inArray(code, codeList) === -1) { //not in array
        codeList.push(code);
    }
});

Fiddle

And as I stated in the question comments, IDs starting with a digit are illegal unless you're using the HTML5 doctype.

Upvotes: 3

Sushanth --
Sushanth --

Reputation: 55750

Try this .. Instead of cheking for bool check for its index.. It returns a -1 when it is not found..

var codeList = [];

jQuery('a').live(
    'click', 
    function()
    {
         var code = '123456-001'; // CHANGES HERE
         if( jQuery.inArray( code, codeList ) < 0) { // -ve Index means not in Array
              codeList.push( code );
              // some specific operation in the application
         }   
    }
);

Upvotes: 4

Related Questions