I am working on a piece of code that would allow me to press different "buttons" to insert a value inside of a text type input of a HTML form.
Currently, I am able to get the code working with one button connected to an event listener to modify the value in the text field, however, when I tried to add multiple buttons to edit the same text field, for some reason, I cannot get it to work.
I've tried different work arounds such as to add individual event listeners to each button and add a parameter field to the main function, however, I still can't get it to work for some reason.
Here's the minimum reproducible code snippets for the HTML and JS:
const textField = document.querySelector('input[name = "textField"]');
var myElement = document.forms['Test']['textField'];
const validTextStrings = ["Hello World", "Goodbye World"]
var button = document.querySelector('input[name = "button"]');
//var button2 = document.querySelector('input[name = "button2"]');
button.addEventListener("click", updateTextField);
function updateTextField() {
console.log("button pressed");
console.log(button.value);
if (allValidValues(button.value)) {
myElement.setAttribute('value', button.value);
}
}
function allValidValues(value) {
for (i = 0; i < validTextStrings.length; i++) {
if (value == validTextStrings[i]) {
return true;
}
}
console.log("Invalid value");
return false;
}
<body>
<form name="Test">
<input type="button" name="button" value="Goodbye World" class=".btn">
<input type="button" name="button2" value="Hello World" class=".btn">
<input type="text" value='TEST' placeholder="TEXT NEEDS UPDATING" name="textField">
</form>
</body>
class=".btn"add the.same.button.listener passing theirvalueto a text.field.update.function called by the listener.