Skip to content Skip to sidebar Skip to footer

How To Pass Objects In Parameters In Onclick() Event?

I have this function: function createMarkersForPlaces(places, infowindow) { for (var i = 0; i < places.length; i++) { var place = places[i]; var marker = new google.ma

Solution 1:

marker is an object, so you won't be able to convert it to a string to be put into the onclick attribute, and it's outside of the window scope, so you won't be able to do it directly in the onclick attribute anyways. I would probably do it like this:

var $li = $("<li><a href='#' class='w3-bar-item'>" + place.name + "</a></li>");
$("ul").append($li);
$li.on('click', getPlacesDetails.bind(this, marker, infowindow));

Solution 2:

First, your concatenation is wrong. You need to concatenate the variable into the string by terminating the string, concatenating the variable and then adding another string. Don't forget + between every concatenation:

onclick='getPlacesDetails("' + marker + '","' + infowindow + '")'

Second, all this will do is concatenate the entire object into your string, not some actual usable string property of that object.

Now, you should not use inline HTML event attributes for event binding. That was how we did it 100 years ago and there are many reasons not to do it. Instead, do all your event binding in script. This will also allow you to avoid the concatenation completely.

Lastly, don't use a hyperlink if you aren't actually navigating anywhere. It's semantically incorrect and you have to disable the native click behavior of the link, not to mention that it can cause problems with the browser's history. Just about any visible element can be clicked, so just bind click to the li and forget the a completely:

var li = document.createElement("li");    // Create the element in memory
li.classList.add("w3-bar-item");          // Configure the CSS// Set up the click event to an anonymous function that calls the// actual function you want and passes the parameters it needs:
li.addEventListener("click", function(){ 
   getPlacesDetails(marker, infowindow)
});

Post a Comment for "How To Pass Objects In Parameters In Onclick() Event?"