0

I want to run a function inside a few quotes and double quotes but it's not working

document.getElementById("loggedin")
.innerHTML="welcome " + user + "<a onclick=deletecookie()> yes </a>";
Tiny
  • 27,221
  • 105
  • 339
  • 599
KiaN
  • 33
  • 2
  • 8

2 Answers2

1

It should be

document.getElementById("loggedin")
    .innerHTML="welcome " + user + "<a onclick='deletecookie()'> yes </a>";

Refer to this question for why quotes should be included around HTML5 attributes.

Generally speaking though, it's better to bind something like this via a jQuery event listener within your javascript code rather than injecting it into the DOM. For example:

document.getElementById('loggedin')
    .innerHTML = "welcome " + user + "<a> yes </a>";
$('#loggedin').on('click', 'a', deletecookie);

This keeps your javascript isolated from your rendered HTML and makes it clearer how things are set up for future development.

Community
  • 1
  • 1
astex
  • 1,045
  • 10
  • 28
  • 1
    Why are the quotation marks necessary? What is `$`? – Felix Kling Apr 28 '14 at 18:25
  • Quotation marks are necessary for cross-browser support. $ is jQuery, but I suppose you could do this with straight javascript as well. – astex Apr 28 '14 at 18:26
  • Maybe you should explain what jQuery is and add a link. Which browsers have problems with unquoted attribute values? Quotation marks for attribute values are optional in HTML, unless the value contains invalid characters (such as a space). – Felix Kling Apr 28 '14 at 18:41
0

Or you could use escaped double quotes, as shown below.

document.getElementById("loggedin").innerHTML="welcome " + user + "<a onclick=\"deletecookie()\"> yes </a>";
yvanavermaet
  • 348
  • 1
  • 9
  • It's best if you show us a testcase. I created an example of the above code in jsfiddle (http://jsfiddle.net/yvanavermaet/46gfM/) and it works fine. – yvanavermaet Apr 28 '14 at 18:28
  • it just says "welcome g%40yahoo.com yes" and when you click on yes, nothing happens – KiaN Apr 28 '14 at 18:29
  • Open the console of your browser. The piece of code I wrote will output the message "delete cookie". – yvanavermaet Apr 28 '14 at 18:31
  • you mean i click ctrl + shift + j and paste exactly what you wrote?? – KiaN Apr 28 '14 at 18:34
  • You should update your piece of code (as written in your initial question) with my piece of code. If that doesn't work for you, then I believe you have an error somewhere else. Can you either explain in full what isn't working or provide an example? – yvanavermaet Apr 28 '14 at 18:37
  • it just says "welcome g%40yahoo.com yes" and when you click on yes, nothing happens – KiaN Apr 28 '14 at 18:40
  • Have you written a javascript function called "deleteCookie"? – yvanavermaet Apr 28 '14 at 18:41