Reputation: 54
I'm trying to display a number (1, 2, or 3) in my html file when I click a button.
Here is what I have so far:
<tr>
<td><button onclick="setDay(1)">1</button></td>
<td><button onclick="setDay(2)">2</button></td>
<td><button onclick="setDay(3)">3</button></td>
</tr>
<script type="text/javascript">
function setDay(a) {
var day = a
}
document.write(day)
</script>
I want to have it so when I click "button '1' ", for example, the function setDay() runs, with my argument set to 1. This way, the variable "day" is set to 1, and then when the variable 'day' is printed the number 1 is displayed. Any help would be greatly appreciated.
Upvotes: 0
Views: 1902
Reputation: 15665
It's not clear whether you want the 1,2,3 to appear on the buttons when clicked or in a new spot. either way you want to pass the event and the number to your function. Then set innerHTML of the element you want the number to appear in.
function setDay(event,a) {
e=event.target;
e.innerHTML = a;
var div = document.getElementById('here');
var text = div.innerHTML;
div.innerHTML = text + " " + a;
}
button{
height:36px;
width:36px;
vertical-align:top;
}
<tr>
<td><button onclick="setDay(event,1)"></button></td>
<td><button onclick="setDay(event,2)"></button></td>
<td><button onclick="setDay(event,3)"></button></td>
</tr>
<div id="here"></div>
Upvotes: 0
Reputation: 1471
There are multiple things wrong with your code:
You are declaring the day variable inside your function, so whenever the function completes, the variable will be destroyed. So to persist it, move it outside the function and set it from inside.
document.write
will clear your document and replace it with whatever you specify. Hence you need to have another element on which you can display the day.
The code should be:
var day;
function setDay(a) {
day = a;
document.getElementById('day').innerHTML = day;
}
<tr>
<td><button onclick="setDay(1)">1</button></td>
<td><button onclick="setDay(2)">2</button></td>
<td><button onclick="setDay(3)">3</button></td>
</tr>
Day : <p id='day'></p>
The document.getElementById('day')
gets the element where you want to display your day, a paragraph tag here, and sets its innerHTML
or the html inside the element to be the specified day.
Upvotes: 1