CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   Resolved problem with accessing onclick attribute (http://www.codingforums.com/showthread.php?t=250980)

BirdIsTheWord 02-08-2012 04:03 AM

problem with accessing onclick attribute
 
What I am trying to achieve, is a button that calls a function that changes the onclick attribute of that button, so that when it is clicked again, it resets the onclick attribute to call the default function. here is what the stripped down code looks like:
Code:

<html>
<head>
<script type="text/javascript">
function remove_prep(a){
a.value="cancel";
a.onclick="cancel_remove(this);";
}
function cancel_remove(a){
a.value="remove";
a.onclick="remove_prep(this);";
}
</script>
</head>
<body>
<input type="button" value="remove" onclick="remove_prep(this);" />
</body>
</html>

for some reason, it only fires once, after which it ceases to work properly.


thanks for the help this part of my code is killing me.

xelawho 02-08-2012 04:19 AM

you want it to be able to flip back and forth infinitely?
Code:

<html>
<head>
<script type="text/javascript">
var clicked=false;
function duck(){
alert("wabbit season")
clicked=true;
}
function wabbit(){
alert("duck season")
clicked=false;
}
</script>
</head>
<body>
<input type="button" value="click me!" onclick="clicked==false?duck():wabbit()" />
</body>
</html>


BirdIsTheWord 02-08-2012 04:23 AM

yes, this is great, thank you!

xelawho 02-08-2012 04:31 AM

:thumbsup: you're welcome. there's actually lots of ways to do this. here's another which is a bit closer to what you were trying:

Code:

<html>
<head>
<script type="text/javascript">

function duck(btn){
alert("wabbit season")
btn.onclick=function(){wabbit(btn)}
}
function wabbit(btn){
alert("duck season")
btn.onclick=function(){duck(btn)}
}
</script>
</head>
<body>
<input type="button" value="click me!" onclick="duck(this)" />
</body>
</html>


BirdIsTheWord 02-08-2012 04:36 AM

thank you, seriously I've been puzzled over why it didn't work for the past two days, now I can focus on other things, like sleep

Dormilich 02-08-2012 06:59 AM

just remember that the HTML event attributes are not the same as the JavaScript event properties. the former require a parseable JavaScript expression/statement, while the latter require a function. there are also differences in the used scope and automatically passed parameters.

PHP Code:

function test()
{
    
alert(this); // show scope
    
alert(arguments[0]); // show 1st passed parameter


PHP Code:

<button type="button" id="a_button" onclick="test();">click me</button>
<
button type="button" id="another_button">click me</button>
<
script type="text/javascript">
document.getElementById("another_button").onclick test;
</script> 



All times are GMT +1. The time now is 10:06 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.