Ayush
Ayush

Reputation: 173

How to print array data in alert

saveData: function()
    {

        var element = $('input');
        for(var i=0;i<element.length;i++)
        {
            //alert($(element[i]).val());
            var p=new Array($(element[i]).val());
        }
        alert(p);

    },

How to print array data in alert.

Upvotes: 1

Views: 59440

Answers (6)

You can use join().

It converts each array element into a string. It acts much like toString(), moreover you can determine the separator.

var arr = ["HTML","CSS","JS"]; 
...
alert(arr.join(' - '));

Upvotes: 0

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

Use javascript forEach() function to get result

var array = ["a","b","c"]; 

solution:

array.forEach(function(data){alert(data)});

Upvotes: 0

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

Use javascript toString() function to get result

var array = ["a","b","c"];

solution:

alert(array.toString());

Upvotes: 5

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

To display array values properly try this :

saveData: function()
    {
        var p=new Array();
        var element = $('input');
        for(var i=0;i<element.length;i++)
        {
            //alert($(element[i]).val());
            p[0] = $(element[i]).val();
        }
        alert(p.join("\n"));

    },

Upvotes: 0

James
James

Reputation: 1019

In JavaScript you could just

for(i=0; i<p.length; ++i){
    alert(p[i]);
}

so if p is an array containing ["one","two","three"] your browser will alert "one", "two" and then "three" in the loop.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388366

You need to create an array and then push all the values to it, instead you are resetting it in the loop

var element = $('input');
var p = element.map(function () {
    return this.value
}).get();
alert(JSON.stringify(p));//or alert(p);

changing your code will be

var element = $('input');
var p = [];
for (var i = 0; i < element.length; i++) {
    p.push($(element).eq(i).val());
}
alert(JSON.stringify(p));//or alert(p)

Upvotes: 5

Related Questions