Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable into onclick function in Javascript not working

I've got code involving Google markers. I want to create a button inside infowindow where when you click on it, it calls a function. But the variable I'm passing into it isn't recognised. And when I use Chrome's console, it shows the error:

roadside_parking_adjust:1 Uncaught ReferenceError: marker_lat is not defined at HTMLInputElement.onclick (roadside_parking_adjust:1)

Here's my code:

marker2.addListener('click', function() {
    var marker_lat = this.getPosition().lat();
    var marker_lng = this.getPosition().lng();

    var save_coord_btn = "<input type='button' onClick='saveCoordinates(marker_lat, marker_lng, 12345)' class='btn' value='儲存經緯度'></input>";

    infowindow.setContent("<div style='text-align:center;'>"+save_coord_btn+"</div>");
    infowindow.open(map, this);
});
like image 529
Ben Kao Avatar asked Jan 29 '26 23:01

Ben Kao


1 Answers

Once the info window content is displayed on the map, the onClick handler won't have access to the variables defined at the top of the marker click handler (marker_lat and marker_lng).

So instead of

"... onClick='saveCoordinates(marker_lat, marker_lng, 12345)' ..."

concatenate the values of marker_lat and marker_lng to the save_coord_btn string like this:

"... onClick='saveCoordinates(" + marker_lat + "," + marker_lng + ", 12345) ...'

or you could use template literals like this:

`... onClick='saveCoordinates(${marker_lat}, ${marker_lng}, 12345)' ...`

Take a look at this JSBin for a working example.

like image 147
Iavor Avatar answered Jan 31 '26 16:01

Iavor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!