Link to home
Start Free TrialLog in
Avatar of Thread7
Thread7

asked on

Dynamically changing a javascript onclick value

I have tried unsuccessfully to dynamically change the onlick value that is currently in an <a> tag.  It seems like the code below should work but I get an error at: thisoc =  allLinks[i].onclick;

Thanks.
---HTML---
<a href="http://www.mysite.com/somepage.php?id=381" onclick="function1();">Some text to click</a>
 
---Javascript in my function---
 
    allLinks = document.getElementsByTagName('a');
	for (var i = 0; i < allLinks.length; i++) {
	    thislink = allLinks[i].href;
            thisoc =  allLinks[i].onclick;  //This statement produces an error
 
            if(thislink.indexOf('somepage.php') > 0) {
              //Need to insert our own function call in the onclick part
              thisoc.replace(/function1/gi, "alert('zvc');function1");
              allLinks[i].onclick = thisoc;
            }
	}

Open in new window

Avatar of alexpercsi
alexpercsi
Flag of Romania image

The problem is that calling thisoc=allLinks[i].onclick will not produce a string value in thisoc, it will produce a reference to the function.

You can try something like this:

allLinks[i].onclick=function(){alert('zvc');function1();}

Open in new window

You may like to check out this code about the technique
<html>
<head>
<script language="javascript">
function saybye() 
{
alert("bye!");
}
 
function change()
{
var me = document.getElementById('field2');
alert(me.attributes['onclick'].value);
me.onclick = function() {saybye()};
}
</script>
</head>
<body>
 
Field2: <input type="text" id="field2" onclick="alert('hi');">
<br /><br />
Click the button below to change method of onclick.
<br />
<button onclick="change();">Change</button>
 
 
</body>
</html>

Open in new window

Avatar of Thread7
Thread7

ASKER

Hmm, I don't think the statement

thisoc=allLinks[i].onclick;

even creates a reference to the function.  My code stops running at that line.  I tried putting this line instead but it also stops my code at this point.

thisoc = allLinks[i].attributes['onclick'].value;
ASKER CERTIFIED SOLUTION
Avatar of alexpercsi
alexpercsi
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thisoc = allLinks[i].attributes['onclick'].value; will not work because the attributes collection is not supported correctly on most browsers.