0

In JS, I am creating a link where the href attribute runs a function. The function simple opens an alert window with a given variable.

function alerter(str){
    alert(str);
}

When I create the link, I use the following code.

var link = document.createElement('a');
link.setAttribute('href','javascript:alerter("hi")');
link.innerHTML = "Sauce";

If I do that, it works. However, what I want to do is alert a previously defined variable. But when i use

link.setAttribute('href','javascript:alerter(myvar)');

the popup no longer works. Also, is there a way to simply embed the alert in the href instead of writing a separate function?

Wilson
  • 8,570
  • 20
  • 66
  • 101

5 Answers5

1

It should be

link.setAttribute('href','javascript:alerter("' + myvar + '")');

You're using string concatenation to put myvar into that string. The way you had it, the whole thing is a string "javascript:alerter(myvar)"

sachleen
  • 30,730
  • 8
  • 78
  • 73
0

Try this

link.setAttribute('href','javascript:alerter('+myvar+')');
yogi
  • 19,175
  • 13
  • 62
  • 92
0

http://jsfiddle.net/xmBbw/2/

Just modify the onclick event of your anchor. If you are not going to link anywhere, you need not use the href attribute. Rather use onclick and assign any function you like to it. Besides, it's awfully bad practice to write javascript inside an html tag. Please don't.

A nice article regarding good practices

Community
  • 1
  • 1
Pablo Mescher
  • 26,057
  • 6
  • 30
  • 33
0

The myvar variable has to be in the global scope. Be sure you can also access it as window.myvar.

J. K.
  • 8,268
  • 1
  • 36
  • 35
0

for your first question use :

link.setAttribute('href','javascript:alerter(' + somevar + ')');

and for your second question use:

link.setAttribute('href','javascript:alert(' + somevar + ')');

cheers.

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63