I'm trying to call javascript function (without argument) through href it works fine but same function call (with argument) it through error unexpected end of input
infowindow.setContent("<table><tr><th>Name</th><td><a href='javascript:Institute('"+code+"')'>" + text + "</a></td></tr><tr><th>IP Address</th><td>" + ip + "</td></tr><tr><th>Code</th><td><a href='javascript:Institute();'>" + code + "</a></td></tr></table>");
3 Answers 3
This should work:
infowindow.setContent('<table><tr><th>Name</th><td><a href="javascript:Institute(\''+code+'\')">' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:Institute();">' + code + '</a></td></tr></table>');
This way the result HTML has double quotes (") for tag attributes and single quotes (') for JavaScript strings, which is the best way to ensure no conflicts arise.
To demonstrate, this uses document.write() and alert() in stead but works if you click Run code snippet
var code = 'The Code';
var text = 'The Text';
var ip = 'The IP';
document.write('<table><tr><th>Name</th><td><a href="javascript:alert(\''+code+'\')">' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:alert(\'empty string\');">' + code + '</a></td></tr></table>');
Comments
You have a problem with your quote.
Use : <a href='javascript:Institute(\'"+code+"\')'>
You could easily find it, if you use the HTML debugger from your web browser.
Comments
infowindow.setContent('<table><tr><th>Name</th><td><a href="javascript:Institute(\""+code+"\");' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:Institute();">' + code + '</a></td></tr></table>');
createElement. UsecreateTextNode. UseappendChild. UseaddEventListener. Your code will be more verbose but infinitely easier to understand, debug and maintain.createElement. I agree thataddEventListenerwould be a better option though, OP could get the best of both by giving the clickable elements anid="some_button_id"and thendocument.getElementById('some_button_id').addEventListener(...)