How to force a javascript function to treat a parameter as string? -


<script>  var id = "432.000+444"; myfunc(id); document.write("<a onclick=\"myfunc("+id+");\" href=#>click me</a><br>");  function myfunc(id) {     alert(id); }  </script> 

myfunc(id) prints string normally, clicking on element prints 876 (treats number , adds 432 , 444). how can prevent this? want treated string.

put in quotes:

document.write("<a onclick=\"myfunc('"+id+"');\" href=#>click me</a><br>"); // ---------------------------------^------^ 

fwiw, advise not using onxyz-attribute-style event handlers. 1 thing, functions call them have globals, not thing. instead, use modern event handling (addeventlistener, or attachevent on old ie; here's function handles issue) or @ least onclick property.

var id = "432.000+444"; var link = document.createelement("a"); link.onclick = myfunc.bind(link, id); link.href = "#"; link.appendtextnode("click me"); appropriateparentelement.appendchild(link); appropriateparentelement.appendchild(document.createelement("br"));  function myfunc(id) {     alert(id); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -