What am I doing wrong here (http://jsfiddle.net/dsqBf/2/)?
I’m trying to put the value of the clicked button into the text input. If you click any button, the value of the last button is inserted into the text input.
JavaScript code:
var theButtons = $(".button");
$(theButtons).each(function(index) {
currentButton = $(this);
buttonValue = currentButton.val();
currentButton.click(function() {
$("#theinput").val(buttonValue);
});
});
Am I missing a concept I’m not aware of? Thanks!
Prefix
currentButtonbyvar. Without it, the variable’s value will be assigned to a variable in the global scope, because you haven’t declaredcurrentButtonanywhere else. Consequently, the value ofcurrentButtonis changed to the value of the last button (because there’s only one variable).Other notes:
thebuttonsis 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.this.valueinside the click handler.each, you can also bind aclickhandler on the selector.Recommended code (demo: http://jsfiddle.net/dsqBf/11/)
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.