Sahil Grover
Sahil Grover

Reputation: 1915

how to make and acess array in jquery

var buttons =$('input[type="button"]');
var arr = (buttons).makeArray;
for(i=0;i <= arr.length ; i++  )
{ $('.chat_tabs').append(arr[i]).val() ;}

this is not working , it this the correct way , what else should i do, have seen many questions but not able to co-relate and get my self right, in first line a had extracted the all DOM elements which are button type i want to extract value from all of them and also run a loop to print them all or even if want to compare or do any thing else....main concern is to make them array and extract values while running loop.

Upvotes: 1

Views: 734

Answers (2)

Rafay
Rafay

Reputation: 31033

$('input[type="button"]').each(function(){

    $("div").append($(this).val()+"<br/>");
    //alert($(this).val());

});

here is the fiddle http://jsfiddle.net/d9xQP/2/

have alook at .each

here is your code

var buttons =$('input[type="button"]');
for(i=0;i < buttons.length ; i++  )
{

    $('.chat_tabs').append(buttons.eq(i).val()+"<br/>");
}

http://jsfiddle.net/d9xQP/4/

Upvotes: 2

Sam Martin
Sam Martin

Reputation: 1248

There are a few things wrong with your code, but I'm guessing you want to do something like this?

Code

var buttons =$('input[type="button"]');
var arr = $.makeArray(buttons);

for(i=0;i <= arr.length ; i++  )
{ $('.chat_tabs').append($(arr[i]).val()) ;}

jsFiddle Demo

Explanation

  • Makearray has to be called with the thing you want to be made into an array INSIDE the parentheses.
  • You had your .val() after your append, I'm assuming you wanted to get the value of the button rather than the value of the append.

Better Option

However, this all can be accomplished more succinctly by using something like this:

var arr = $('input[type="button"]').map(function(){return $(this).val();}).get();
$('.chat_tabs').append(arr.join(' '));

jsFiddle Demo
jQuery Api on .map()
jQuery Api on .get()

Upvotes: 1

Related Questions