Missing] after list of json items

I am trying to call the getPointOnMap function in an onclick event and give it a json object as a parameter.

Here are some sample code:

 $.ajax({ type: "POST", url: "/getResult.json", success: function(result) { var html = ''; for (var i = 0; i < result.length; i++) { var obj = result[i]; html += "<input type='checkbox' onClick='getPointOnMap(" + obj + ")'/>" + obj.address + "<br>"; } $("#myDiv").append(html); } }); 

there is a getPointOnMap function

 function getPointOnMap(object) { map.addMarker({ lat: object.lattitude, lng: object.longtitude, click: function(e) { alert('You clicked in this marker'); } }); } 

firebug output (also in the name question):

SyntaxError: missing] after list of items

 getPointOnMap([object Object]) 

What should I do to pass the correct object?

+4
source share
3 answers

I don’t think it’s allowed to rewrite the question, anyway you have to create your HTML input not through the line, but through the DOM so that you can bind the handler to a function, and not to "onclick".

 $.ajax({ type: "POST", url: "/getResult.json", success: function(result) { for (var i = 0; i < result.length; i++) { (function (n) { var obj = result[i], element = $("<input>", {type: "checkbox"}); element.click(function () { getPointMap(obj); }); $(document.body).append(element, obj.address + "<br />"); })(i) } } }); 
+4
source

Ok, simple way:

 html += "<input type='checkbox' onClick='getPointOnMap(" + obj.lattitude + ", " + obj.longtitude + ")'/>" + obj.address + "<br>"; function getPointOnMap(lat,lng) { map.addMarker({ lat: lat, lng: lng, click: function(e) { alert('You clicked in this marker'); } }); } 
0
source
 $.ajax({ type: "POST", url: "/getResult.json", success: function(result) { var myDiv = $('#myDiv'); $.each(result, function(i, obj) { myDiv.append( $('<INPUT>').attr('type', 'checkbox').on('click', function() { getPointOnMap(obj); }, obj.address, "<br>" ); }); } }); 
0
source

Source: https://habr.com/ru/post/1483355/


All Articles