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.
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;
}
}
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>
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['on click'].va lue;
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['on
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
thisoc = allLinks[i].attributes['on click'].va lue; will not work because the attributes collection is not supported correctly on most browsers.
You can try something like this:
Open in new window