const one = document.getElementById("one");
// const input = document.getElementById("input");
one.addEventListener('click', function() {
// document.forms[0].input.value = '1';
document.getElementById("input").value = 1;
});
main {
display: grid;
grid-template-columns: 60px 60px 60px;
grid-template-rows: 60px 60px 60px 60px;
}
#clear {
grid-column: 2/4;
grid-row: 4/5;
border: 1px solid blue;
}
div {
border: 1px solid blue;
text-align: center;
font-size: 24px;
background-color: lightgreen;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="form1">
<input id="input" name="input">
</form>
<main>
<div id="one">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>0</div>
<div id="clear">CLEAR</div>
</main>
</body>
</html>
I tried creating buttons using css grid and javascript to put a value to an input box but it doesn’t work. I tried this:
document.getElementById("one").value = 1;
I also tried
document.forms[0].input.value = 1
This is like a calculator problem. You input numbers to an input box by clicking on the number buttons.
3
Answers
Reason1:
Your issue seems to be that script written on head element, trying to access elements before they are fully loaded.this is the reason everyone writes the javascript at the end of body to ensure that script runs after the once DOM is fully loaded.just replace the script after the body.
The result will be following error for accessing a dom element before it was defined
Reason2:
The script may not fully loaded in the browser to update the changes in the script manually refresh the browser using ctrl+f5
Actually, your code works. I copy-pasted your code to CodePen and it works. Try refreshing the page or clearing cache.
Note: By default, the input box type is "text".