Dan
Dan

Reputation: 2174

unable to convert plain array into jquery array

On load I have to disable the NEXT button, but for that I have to convert my plain array into jquery array.

http://jsfiddle.net/2hBUq/1/

I tried but its showing some strange value in console. So please help me with this

html

<div id="wholeRecipeIds">
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]
</div>
 <input id="next" width="100px" type="button"  value="Next">

jquery

var nextRowIndex = '32661'; 
var wholeRecipes=$("#wholeRecipeIds").html();
var recipArray = jQuery.makeArray(wholeRecipes); 
var lastRecipeId =  recipArray[recipArray.length-1];

console.log("New array recips:"+recipArray);   
console.log("size of array recipe:"+recipArray.length);   
console.log("lastRecipeId in array :"+lastRecipeId);  
if(nextRowIndex==lastRecipeId){
   $("#next").attr('disabled','disabled');
}

output:(wrong output for "size of array recipe & lastRecipeId variable)

New array recips:
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]
 (index):28
size of array recipe:1 
lastRecipeId in array :
    [3618, 5143, 5144, 5146, 9728, 16497, 4002, 4852, 2864, 32661]

Why this strange output.

Upvotes: 1

Views: 78

Answers (3)

laaposto
laaposto

Reputation: 12213

jQuery.makeArray() turns an array-like object into an array

Use JSON.parse() to convert a string into an array.

Try:

var recipArray = JSON.parse(wholeRecipes); 

instead of

var recipArray = jQuery.makeArray(wholeRecipes); 

DEMO

Upvotes: 1

Torsoe
Torsoe

Reputation: 160

makeArray Convert an array-like object into a true JavaScript array.

    var nextRowIndex = '32661'
        wholeRecipes=$("#wholeRecipeIds").html(),
        recipArray = $.parseJSON(wholeRecipes), 
        lastRecipeId = recipArray[recipArray.length-1];

    console.log("New array recips:"+recipArray);   
    console.log("size of array recipe:"+recipArray.length);   
    console.log("lastRecipeId in array :"+lastRecipeId);  
    if(nextRowIndex==lastRecipeId){
       $("#next").attr('disabled','disabled');
   }

Upvotes: 0

Pointy
Pointy

Reputation: 413712

You're not starting off with an array; you're starting with a string. The contents of the <div> are read as just one simple string. If you want it to be interpreted as an array, you can feed it to the JSON parser:

    var wholeRecipes = JSON.parse($("#wholeRecipeIds").html());

There's not really any need to do this:

    var recipArray = jQuery.makeArray(wholeRecipes); 

Once you've parsed the raw contents of your element, you'll have a JavaScript array. There's really no such thing as a "jQuery array", and that's not what that API is for.

Upvotes: 1

Related Questions