Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  115] [ 3]  / answers: 1 / hits: 15108  / 9 Years ago, sun, june 21, 2015, 12:00:00

When I click numbers, I always get the same result. Why? Here is my HTML code:





<!DOCTYPE html>
<html>
<body>
<p id=demo></p>
<input type=button id=myBtn onclick=myFunction() value=1>
<input type=button id=myBtn onclick=myFunction() value=2>
<input type=button id=myBtn onclick=myFunction() value=3>
<input type=button id=myBtn onclick=myFunction() value=4>
<input type=button id=myBtn onclick=myFunction() value=5>
<input type=button id=myBtn onclick=myFunction() value=6>
<input type=button id=myBtn onclick=myFunction() value=7>
<input type=button id=myBtn onclick=myFunction() value=8>
<input type=button id=myBtn onclick=myFunction() value=9>
<input type=button id=myBtn onclick=myFunction() value=0>
<script>
function myFunction() {
var x = document.getElementById(myBtn).value;
document.getElementById(demo).innerHTML = x;
}
</script>
</body>
</html>




More From » html

 Answers
18

1) Ids must be unique. Rewrite your HTML to use classes or unique ids.



2) To get value in myFunction you can simply pass this from elenment to access to clicked button.



<input type=button id=myBtn onclick=myFunction(this) value=1>

....

function myFunction(button) {
var x = button.value;
document.getElementById(demo).innerHTML = x;
}


http://jsfiddle.net/0sewtjLs/







Still have the problem in case of more than 1digit number




Just concat string:



document.getElementById(demo).innerHTML += x;


http://jsfiddle.net/0sewtjLs/1/


[#66114] Friday, June 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;