...

View Full Version : How to send variables value?



Quarath
12-09-2011, 09:15 AM
I need to add onclick event to an element => myFunction(myVariable) but instead of the myVariable I need it's value to be set as an attr. As in:

<!html>
<head>
</head>
<body>
<input type="button" id="element" value="click me!">
<script type="text/javascript">
var myVariable = "myvalue";
document.getElementById('element').onclick = function () {
showIt(myVariable);
}
myVariable = "myvalue2";

function showIt(msg){
alert(msg);
}
</script>
</body>
</html>
Now i need the "click me!" input to alert "myvalue" and not "myvalue2".

Old Pedant
12-09-2011, 09:29 AM
In other words, you want it to alert the value of myVariable at the time the onclick was set up, not whatever value it gets later, right?

The easiest way to do this would be to simply copy it to another variable that you don't use for any other purpose and alert that, instead.

But, yes, it can be done. It requires a closure to make it work.


var myVariable = "myvalue";

function setUpOnClick(withThis)
{
var handler = function () { showIt(withThis); };
return handler;
}
document.getElementById('element').onclick = setUpOnClick(myVariable);

myVariable = "something else and it won't affect the onclick's message";

Philip M
12-09-2011, 09:36 AM
<input type="button" id="element" value="click me!">
<script type="text/javascript">
var myVariable;
document.getElementById('element').onclick = function () {
myVariable = "myvalue";
showIt(myVariable);
}
myVariable = "myvalue2";

function showIt(msg){
alert(msg);
}
</script>


Quizmaster: In medicine, a cochlea implant is designed to stimulate which of the five senses?
Contestant: Could you repeat the question, please?

Quarath
12-09-2011, 04:34 PM
Looks like I oversimplified the example. None of these will work for me :(
This code (in reality it's much more complex...hope i didn't mess it up simplifying it again) will better explain what I need:

for(var i = 0; i < x; i++) {
document.getElementById('field-' + i).onchange = function () { myFunction(i); }
}

Amphiluke
12-09-2011, 04:57 PM
As Old Pedant suggested, you may get a solution by using a closure


for(var i = 0; i < x; i++) {
document.getElementById('field-' + i).onchange = (function (index) {
return function() { myFunction(index); };
})(i);
}

Quarath
12-12-2011, 10:51 AM
Thats it! Thank you.


As Old Pedant suggested, you may get a solution by using a closure


for(var i = 0; i < x; i++) {
document.getElementById('field-' + i).onchange = (function (index) {
return function() { myFunction(index); };
})(i);
}

Kevin2moon
12-12-2011, 11:48 AM
Thanks a lot too.It helps me lot too.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum