Reputation: 1
I am having trouble displaying a variable value in a input/text box.Variable gold is the one i want to display in a input since its updating every second but i am having issues.I am able to display it as a text in html though..Sorry if i am a bit unclear..
<!DOCTYPE html>
<html>
<head>
<title>Money System</title>
<div id="gold"></div>
<div id="goldpersecond"></div>
<div id="lvl"></div>
<script>
var gold = 0;
var goldpersecond = 0;
var lvl = 1;
//end of variables list
function lvlup(){
lvl = lvl + 1;
goldpersecond = lvl - 1;
if (goldpersecond >= 1){
window.setInterval(
function () {
gold = gold + goldpersecond;
document.getElementById("gold").innerHTML = "You have " + gold + " gold!";
}, 1000);
document.getElementById("lvl").value = lvl;
}
}
</script>
</head>
<body>
<input type="text" value="Level" disabled name="test">
<input type="text" value="0" id="lvl" readonly/>
<br>
<input type="text" value="Gold" disabled name="test"></input>
<input type="text" value="0" id="Gold" readonly/>
<br>
<button type="button" onClick= "lvlup()" />Level Up!</button>
</body>
</html>
Upvotes: 0
Views: 61
Reputation: 601
You are referencing the 'div' defined in the 'head' and not the input from the body.
Get rid of the 'div' elements inside head and it will work
See https://jsfiddle.net/vdgzs1db/1/
<!DOCTYPE html>
<html>
<head>
<title>Money System</title>
<script>
var gold = 0;
var goldpersecond = 0;
var lvl = 0;
//end of variables list
function lvlup(){
lvl = lvl + 1;
document.getElementById("lvl").value = lvl;
goldpersecond = lvl - 1;
if (goldpersecond >= 1){
window.setInterval(
function () {
gold = gold + goldpersecond;
document.getElementById("gold").innerHTML = "You have " + gold + " gold!";
}, 1000);
}
}
</script>
</head>
<body>
<input type="text" value="Level" disabled name="test">
<input type="text" value ="0" id="lvl"/>
<br>
<input type="text" value="Gold" disabled name="test"/>
<input type="text" value="0" id="Gold"/>
<br>
<button type="button" onClick= "lvlup()">Level Up!</button>
</body>
Upvotes: 0
Reputation: 1086
If your field is updating every second, an input field is not a useful place to display the value. Use a regular HTML display element (paragraph, span, etc.) and update it there. Keep the input box for input.
It would be a rare user who could enter and submit a usable value from an input box if you are overwriting it every second.
If you want the display to look like an input box, add CSS styles to make it look the same. It may be confusing to the user, but if that is what you want, styling a display element is a better solution than continuously updating their input.
Upvotes: 1