max cheng
max cheng

Reputation: 181

Javascript- How to pass array as parameter at onclick event?

I have an array that I want to pass to a javascript onclick function. I send that array in the onclick event of a button. The onclick function return me [object Object]. Is there a different way to do call that function with the array?

Here My Code:

var data_type= $.parseJSON(data_playtype[1]);//{"1":"apple","2":"orange","23":"berry","8":"grape","9":"mango"}


str1.push('<td><a href="javascript:void(0)" onClick="showABC(\''+data_type+'\')">'Data'</td>');



function showABC(fruit){

    $.each(fruit,function(pid,pt){
        alert(pt);
    });

}

Upvotes: 1

Views: 11539

Answers (2)

guest271314
guest271314

Reputation: 1

I have an array that I want to pass to a javascript onclick function. I send that array in the onclick event of a button. The onclick function return me [object Object]. Is there a different way to do call that function with the array?

Note, data_type not appear to be Array at js ; data_type appear to be Object


Try utilizing .on() , calling showABC() within click event handler with data_type as parameter.

var data_playtype = [];

data_playtype[1] = JSON.stringify({
  "1": "apple",
  "2": "orange",
  "23": "berry",
  "8": "grape",
  "9": "mango"
});

var data_type = $.parseJSON(data_playtype[1]);
//{"1":"apple","2":"orange","23":"berry","8":"grape","9":"mango"}

var str1 = [];
str1.push("<td><a href=javascript:void(0)>Data</a></td>");

function showABC(fruit) {

  $.each(fruit, function(pid, pt) {
    alert(pt);
  });

};

$("table tbody").append(str1).find("a")
  .on("click", function() {
    showABC(data_type)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody></tbody>
</table>

Upvotes: 4

PeterKA
PeterKA

Reputation: 24638

DEMO

Using inline JS is not a good idea. I would use a data attribute to hold the data as follows:

var data_type = .....;
var link = $('<a/>').data('data_type', data_type).html('Data');
str1.push( $('<td/>').html( link ) );

//event handler
link.on('click', function(e) {
    e.preventDefault();
    var data_type = $(this).data('data_type');
    .....
});

Ref: https://api.jquery.com/data/

.data( key, value )

key

Type: String A string naming the piece of data to set.

value

Type: Anything The new data value; this can be any Javascript type except undefined.

Upvotes: 0

Related Questions