Ravi Kumar
Ravi Kumar

Reputation: 226

Passing Array or Objects to function convert it to string

Here is my requirement, I have an array having datewise data like

$.each(dateWiseArr, function(index, currentDate){
    myDateArray[currentDate] = "myData";
    dateWiseOtherId[currentDate] = "otherId";
});
alert(myDateArray+"::"+dateWiseOtherId);//working fine and showing right data
$("#myBtn").attr("onClick", "myPassingFunction("+myDateArray+", "+dateWiseOtherId+")");

function myPassingFunction(myDateArray, dateWiseOtherId){
    alert(myDateArray[0]);//throw undefined
}

Now when I am press my button function call successfully but variables becomes string.

Let me know if you need more understanding.

Note: myDate

Upvotes: 0

Views: 217

Answers (3)

Renato Gama
Renato Gama

Reputation: 16519

Right way of binding events: Check this working fiddle http://jsfiddle.net/vC4Yk/

var myDateArray = ["some data"];
var dateWiseOtherId = ["some other data"];

alert(myDateArray+"::"+dateWiseOtherId);//working fine and showing right data

$("#myBtn").click(function(){
   myPassingFunction(myDateArray, dateWiseOtherId);      
});

function myPassingFunction(myDateArray, dateWiseOtherId){
    alert(myDateArray[0]);
}   ​

Upvotes: 0

Tapan
Tapan

Reputation: 108

Try below. It should work.

$.each(dateWiseArr, function(index, currentDate){
    myDateArray[currentDate] = "myData";
    dateWiseOtherId[currentDate] = "otherId";
});

alert(myDateArray+"::"+dateWiseOtherId);//working fine and showing right data

$("#myBtn").click(function (event) {
     myPassingFunction(myDateArray, dateWiseOtherId);
});

function myPassingFunction(myDateArray, dateWiseOtherId){
    alert(myDateArray[0]);//throw undefined
}

Upvotes: 1

Guffa
Guffa

Reputation: 700272

Bind a function instead of binding a string, then you don't need to convert the values to strings:

$("#myBtn").click(function(){
  myPassingFunction(myDateArray, dateWiseOtherId);
});

Upvotes: 1

Related Questions