I have some buttons 1-9 and i want to show their numbers on div called "screen". So i wrote such code, but it not seem to work.
Piece of HTML code with those buttons:
<div id="screen"></div>
<div><input type="submit" class="numKey" id="key7" value="7" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key8" value="8" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key9" value="9" onclick="enterPIN();"></div>
<div style="clear: both;"></div>
<div><input type="submit" class="numKey" id="key4" value="4" onclick="enterPIN();"></div>
<div><input type="submit" class="numKey" id="key5" value="5" onclick="enterPIN();"></div>
(... AND SO ON ...)
JavaScript code:
function enterPIN()
{
for (i=0; i<document.getElementsByClassName("numKey").length; i++)
{
var numKeyId = i + " " + document.getElementsByClassName("numKey")[i].id;
console.log(numKeyId);
return numKeyId;
}
var getElementId = function(numKeyId)
{
this.numKeyId = numKeyId;
document.getElementById("screen").innerHTML = document.getElementsByClassName("numKey")[numKeyId].id;
console.log("Asdasdasd");
}
getElementId();
}
It should work like this:
The first time the for loop iterates (with i=0
), it will get to the return
statement and the function will quit after just one iteration never reaching the last part of the script.
This can be done with less code if you just change the HTML a little bit by putting the value as an argument to enterPin
:
<input type="button" class="numKey" id="key7" value="7" onclick="enterPIN(7);">
Or, as suggested by bcdan, by using this
so you don't have to repeat yourself:
<input type="button" class="numKey" id="key7" value="7" onclick="enterPIN(this.value);">
Do note that I changed from submit
to button
since you do not actually want to submit the form once the buttons are pressed. Then you just need this JS:
function enterPin(number) {
screen = document.getElementById("screen");
screen.innerHTML = screen.innerHTML + String(number);
}
Or, if you want to use jQuery (and get rid of the onclick
attribute):
$(".numKey").click(function() {
screen = $("#screen");
screen.html(screen.html + this.value);
});
Well if you just need it to output what you click, why not do something like
<html>
<body>
<script>
function enterPIN(value)
{
document.getElementById('screen').innerHTML += String(value);
}
</script>
<div id="screen"></div>
<div><input type="submit" class="numKey" id="key7" value="7" onclick="enterPIN(this.value);"></div>
<div><input type="submit" class="numKey" id="key8" value="8" onclick="enterPIN(this.value);"></div>
<div><input type="submit" class="numKey" id="key9" value="9" onclick="enterPIN(this.value);"></div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With