-1

I have some error like

Uncaught SyntaxError: Unexpected end of input

I have error when i put some parameter in function, my code like this

var now = "2018-04-17 11:10:20";
var div = document.createElement("div");
var element = document.getElementById("box");
element.appendChild(div);
div.setAttribute("id", "card"); 
div.setAttribute("onclick", "democlick(", now, ")"); 
var img = document.createElement("img");
var para = document.createElement("p");
var isi = document.createTextNode(datetime);
para.appendChild(isi);
var element_div = document.getElementById("card");
element_div.appendChild(img);
element_div.appendChild(para);
img.setAttribute("src", "markermotor.png");

function democlick(a){
    var now = a;
    console.log(now);
}

Please tell me what wrong with this code ? Thanks

Nugka
  • 301
  • 2
  • 15

1 Answers1

4

The problem is here:

var now = "2018-04-17 11:10:20";
div.setAttribute("onclick", "democlick(", now, ")");

You're providing 4 arguments to setAttribute - the last two are not recognized. Once that line runs, in HTML markup, it looks like

<div onclick="democlick(">

which is invalid syntax. Either put it in a string first and concatenate properly:

div.setAttribute("onclick", "democlick('" + now + "')");

or, better yet: Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code, such as what you're experiencing now. Seriously consider attaching your events with JavaScript instead:

div.addEventListener('click', () => democlick(now));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 2
    This is mostly right, but the attribute is actually just getting the value `democlick(`, since [setAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute) doesn't do anything with additional arguments. Because of that, your first solution should be: `div.setAttribute("onclick", "democlick('" + now + "')");` or `div.setAttribute("onclick", \`democlick("${now}")\`);` – Paul Apr 17 '18 at 04:42
  • Thank it work correctly, this is very helpful :) – Nugka Apr 17 '18 at 04:45