Christopher Littlewood Christopher Littlewood - 29 days ago 9
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" />' +
'</div>';
}


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>' +
'</div>';
}


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.

onclick="showMap(\''+latitude+'\',\''+longitude+'\');furtherDetails(\''+mainImage+'\')

Simple example

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

function bar(c) {
  console.log(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">
Foo
</div>

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) {
  console.log(bar);
}
let bar = 'bar';

let el = document.createElement('div');
el.id = 'resultDiv';
el.appendChild(document.createTextNode('child'));

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

document.getElementById('foo').appendChild(el);
<div id="foo">Foo</div>