-3

Very simply question I can't seem to find solved here.

How can I use javascript to print a hyperlink? I'm very beginner with JavaScript and I need something like the following to work:

document.writeln("<a href="javascript:toggleDummy1();">" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
Matt Andrzejczuk
  • 1,695
  • 6
  • 31
  • 47
  • 3
    I recommend avoiding dynamic html construction in JavaScript if possible. It's much cleaner to use template binding – TGH Sep 17 '13 at 05:30
  • 2
    Don't forget to [avoid `document.write`](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) (when you have learned how to escape strings) – Bergi Sep 17 '13 at 05:48

5 Answers5

2

1) Escape the internal quotes by adding a backslash:

document.writeln("<a href=\"javascript:toggleDummy1();\">" +    
    flaggedKCSarticles.flag_object[i].feedback_text + "</a>");

OR

2) Use single quotes:

document.writeln('<a href="javascript:toggleDummy1();">' +    
    flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
2

Double quotes " are conflicting. Use a single quote in outermost, and double quotes to wrap href attribute.

So it may look like:

document.writeln('<a href="javascript:toggleDummy1();">' + flaggedKCSarticles.flag_object[i].feedback_text + '</a>')
Priya Ranjan Singh
  • 1,537
  • 1
  • 15
  • 27
1

You need to adjust quotes and double quotes so they doesn't conflict.

However, document.write and the like are very poor practice. You will learn soon enough that you need to append in a container rather than "brute print" into a document.

For example:

var a = document.createElement("a");
a.href = "javascript:toggleDummy1();";

// a more semantic way could be:
//
//   a.onclick=function(event){
//       toggleDummy1();
//   }
//

a.innerText = flaggedKCSarticles.flag_object[i].feedback_text;
document.body.appendChild(a);
Frederik.L
  • 5,139
  • 2
  • 22
  • 39
0

There is a problem in your markup, try this

document.writeln("<a href=\"javascript:toggleDummy1();\">" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");

or

document.writeln("<a href='javascript:toggleDummy1();'>" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
nrsharma
  • 2,439
  • 1
  • 16
  • 35
-1

change your syntax like that,

document.writeln('<a href="javascript:toggleDummy1();">' + flaggedKCSarticles.flag_object[i].feedback_text + '</a>');

i hope this will work

Anil Kasar
  • 11
  • 4