I am trying to add some text to an input element using a button. I have so far tried modifying .textContent - which does actually appear to modify the textContent, but this does not show up in the image box. Adjusting the .value does not seem to work.
My code:
const buttons = document.querySelectorAll(".row button");
for (let i = 0; i < buttons.length; i ) {
buttons[i].addEventListener("click", function() {
document.querySelector("input").value = buttons[i].value;
})
}
Every solution I have read online just suggests modifying the .value of the input element, which is not working for me, so I am at a loss.
EDIT: Thanks everyone, such a silly thing to overlook.
CodePudding user response:
Modifying the value property should work for you. Your problem lies in this statement:
value = buttons[i].value
Buttons don't have a value unless you specify one. The inner text of a button is accessed using the innerHTML
or innerText
properties, not the value
property:
const button = document.querySelector("button");
const input = document.querySelector("input");
button.addEventListener("click", (e) => {
input.value = button.innerText;
});
<input type="text" />
<button type="button">bleh</button>
With buttons, the value property is used for PHP form submission, not storing textual data.
CodePudding user response:
Are you trying to set the value for the input field based on the button's display text?
If so, you can attempt to replace buttons[i].value with buttons[i].textContent
CodePudding user response:
You can use button.innerHTML
to assign the input value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<input type="text" value="" />
<button>1</button>
<button>2</button>
<script>
const buttons = document.querySelectorAll("button");
const input = document.querySelector("input");
buttons.forEach((button) => {
button.addEventListener("click", function () {
input.value = button.innerHTML;
});
});
</script>
</body>
</html>