Passing variable in function call

Hi all,

Can anyone point me in the right direction?

I can call a function from a hyperlink as so:

<A HREF=“javascript:go()”>+ Add Text</A>

but how do I pass a variable to the function in this hyperlink?

Any suggestions would be aprreciated.

Thx:)

does this not work?

<A HREF=“javascript:go(‘123’)”>+ Add Text</A>

function go(myval){
alert('x= '+myval);
}

result x= 123

The right direction is to not use the javascript protocol. It does not, nor has ever existed.

Instead, place the function on the onclick event. The cheap-and-nasty way is to use an inline event attribute


<a href="#textTarget" onclick="addText(this)">+ Add Text</a>
<div id="textTarget"></div>

Using the this keyword, means that we pass into the function a reference to the link. That way the addText function can easily gain a reference to the correct link, even if the onclick event is used on multiple links.
Some web browsers differ in how they provide the href value, so it’s best to split the href value at the # symbol, and then take the second part of it (at index 1).


function addText(el) {
    var targetId = el.href.split('#')[1];
    var target = document.getElementById(targetId);
    ...
}

A more modern technique is to not have the scripting intermingled with the HTML code, and to allow the page to work properly even when there is no scripting available.


<div id="textTarget"></div>

Because the add text link is only be useful when scripting is available, it is added with scripting. We can even take the time to add an addTarget property onto the link, so that we can easily get back to the target.


var targetId = 'textTarget';
var target = document.getElementById(targetId);

var a = document.createElement('a');
a.href = '#' + targetId;
a.innerHTML = '+ Add Text';
a.addTarget = target;
a.onclick = addText;

target.parentNode.insertBefore(a, target);

Then from the addText function, the link is accessible via the this keyword


function addText() {
    var link = this;
    var target = link.addTarget;
    ...
}