Christopher Littlewood Christopher Littlewood - 5 months ago 37
HTML Question

Sending a parameter to JS function using .innerHTML

I am attempting to run two different functions which do two separate things. Both need to run when a div is clicked on. The div is generated in the innerHTML function of JavaScript.

This is the method that runs second. It takes one parameter and then generates a div on the page.

//Display larger image:
function furtherDetails(mainImage){
var moreInfo = document.getElementById('divpropertyInfo');
moreInfo.innerHTML = '<div id="propInfoDisplay">' +
'<img id="image" src="'+mainImage+'" alt="Main Image" />' +

This is the code that runs that function:

//Create the property div:
function createPropertyDiv(mainImage, bedrooms, bathrooms, parkings, price, address, latitude, longitude){

var propertyDiv = document.getElementById('divsearchResults');
propertyDiv.innerHTML += '<div id="divResults" onclick="showMap('+latitude+','+longitude+');furtherDetails('+mainImage+');">' +
'<img id="mainImage" src="' + mainImage +'" alt="Main Image" />' +
'<p id="numBedrooms">'+ bedrooms +'</p>' +
'<img id="bedroomsImage" src="/images/bedrooms.png" />' +
'<p id="numBathrooms">'+ bathrooms +'</p>' +
'<img id="bathroomsImage" src="/images/bathrooms.png" />' +
'<p id="numParking">'+ parkings +'</p>' +
'<img id="parkingImage" src="/images/carspots.png" />' +
'<p id="Price">'+ price +'</p>' +
'<p id="addressHeading">Address: </p>' +
'<p id="Address">' + address + '</p>' +

I am getting the error:

Uncaught SyntaxError: missing ) after argument list

Answer Source

The variables inside onclick need to be surrounded by ' or ", otherwise they will be evaluated before the click, leading to your syntax error.


Simple example

let el = document.getElementById('foo');
let f = "bar";

function bar(c) {

el.innerHTML += '<div onclick="bar(\'' + f + '\')">Baz</div>'; // logs the value of f
el.innerHTML += '<div onclick="bar(' + f + ')">Boo</div>'; // logs the function bar
<div id="foo">

That being said, don't use inline javascript. Use an eventListener instead. Then you can just pass whatever you want to the function without having to worry about escaping, and you can call as many functions as you wish from the listener.

function foo(bar) {
let bar = 'bar';

let el = document.createElement('div'); = 'resultDiv';

el.addEventListener('click', function() {
}, false);

<div id="foo">Foo</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download