I want to pass text element (a string) to an on click function:
document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList("+text+");'><a href='#'>"+text;`
ClickStructList is defined as follow:
ClickStructList=function(text){
window.alert("click");
window.alert(text);
};
This doesn't work, firefox debug istelling me: "C is not defined", C is the value of text.
Thanks for any help
PS: I do not want to use jquery
I want to pass text element (a string) to an on click function:
document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList("+text+");'><a href='#'>"+text;`
ClickStructList is defined as follow:
ClickStructList=function(text){
window.alert("click");
window.alert(text);
};
This doesn't work, firefox debug istelling me: "C is not defined", C is the value of text.
Thanks for any help
PS: I do not want to use jquery
Share asked Jul 1, 2015 at 7:11 LaetisLaetis 1,3575 gold badges16 silver badges30 bronze badges 2- What doesn't work? The javascript code itself or when you click on the element? – nils Commented Jul 1, 2015 at 7:13
- when I click nothing happen, if I remove the text argument it works, I get the "click" message. – Laetis Commented Jul 1, 2015 at 7:19
4 Answers
Reset to default 2Try to define your function as a function not variable
function ClickStructList(text){
window.alert("click");
window.alert(text);
};
Also when you define your onClick
callback you should surround it by quotation
<li onClick='ClickStructList("My entered text");'>
so in your example:
.innerHTML="<li onClick='ClickStructList(\""+text+"\");'>
try by changing your JS code to this:
document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList(\""+text+"\");'><a href='#'>"+text;
The quotation marks were missing in your call to ClickStructList ... this works :
var ClickStructList=function (text) {
window.alert("click");
window.alert(text);
};
var text="Hello World";
document.getElementById("struct_list").innerHTML="<li
onClick='ClickStructList(\""+text+"\");'><a href='#'>"+text;
you forgot to add the quote-signs for the string, so JS tries to parse your text as Code.
You need at least sth like this:
... "<li onClick='ClickStructList(\""+text+"\");'><a href='#'>" ...
or even better
... "<li onClick='ClickStructList("+ JSON.stringify(text) +");'><a href='#'>" ...