Prefix currentButton
by var
. Without it, the variable's value will be assigned to a variable in the global scope, because you haven't declared currentButton
anywhere else. Consequently, the value of currentButton
is changed to the value of the last button (because there's only one variable).
var theButtons = $(".button");
theButtons.each(function(index) {
var currentButton = $(this);
var buttonValue = currentButton.val();
currentButton.click(function() {
$("#theinput").val(buttonValue);
});
});
Other notes:
thebuttons
is already a jQuery object, so you should not wrap it in $
again.
$("#theinput")
does probably not change over time. So, I recommend to cache this variable.
- The value of the current button, on the other hand, may change. I suggest to use
this.value
inside the click handler.
- Instead of looping using
each
, you can also bind a click
handler on the selector.
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
$theinput.val(this.value);
});
Prefixed jQuery-variables with $
, because it's the convention to do so. Because of $
, you (and others) know that the variable is a jQuery object, which saves expensive debugging time.