Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Multiple buttons change the value of a single input text field of in a HTML form using JS

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>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You are almost there! Just use the event parameter that contains the value of the target.

Solution

button.addEventListener("click", updateTextField);
button2.addEventListener("click", updateTextField);

function updateTextField(event) {
  console.log("button pressed");
  console.log(event.target.value);
  if (allValidValues(event.target.value)) {
    myElement.setAttribute('value', event.target.value);
  }
}

Every EventListenerCallback has a single param: an object based on Event.

Suggestion

I suggest you to use id than that of class. Using ids it is easier to target a specific element. Another change I did was to create separate eventListeners for the buttons.

You get an event object on the listener function parameter which gives you target value to use. The event object also has other properties to look into.

const textField = document.getElementById('textField');
var myElement = document.forms['Test']['textField'];

const validTextStrings = ["Hello World", "Goodbye World"]


var button1 = document.getElementById('btn1');
var button2 = document.getElementById('btn2');



button1.addEventListener("click", updateTextField);
button2.addEventListener("click", updateTextField);



function updateTextField(event) {

  if (allValidValues(event.target.value)) {
    myElement.setAttribute('value', e.target.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" id="btn1">
    <input type="button" name="button2" value="Hello World" id="btn2" class=".btn">

    <input type="text" value='TEST' id="textField" placeholder="TEXT NEEDS UPDATING" name="textField">
  </form>
</body>

about 4 years ago · Juan Pablo Isaza Report

0

  • I have selected all the buttons by document.querySelectorAll(".btn");

  • Then I have loop through all this buttons and attached click even. I have also bind the ()=>{} updateTextFeild() function inside of the loop.

  • In your code querySelector() will only select the first element so it was selecting only first button.

  • So, whenever you want to select more than one element we must use querySelectorAll or getElementsByClassName.

  • querySelector is only good for selecting specific element like selecting element by id attribute. Lastly, I am not sure but never pass .```` (dot operator) inside of classattribute. Like useclass="btn"instead ofclass=".btn"```.

const textField = document.querySelector('input[name = "textField"]');
var myElement = document.forms['Test']['textField'];

const validTextStrings = ["Hello World", "Goodbye World"]

let buttons = document.querySelectorAll('.btn');

buttons.forEach(button => {
  button.addEventListener("click", () => {
    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>

about 4 years ago · Juan Pablo Isaza Report

0

this is a typical case where you have to use event delegation

const form_Elm = document.forms.Test;

form_Elm.onclick = (evt) =>
  {
  if (evt.target.matches('button')) // verify clicked element tagName
    {
    form_Elm.textField.value = evt.target.textContent
    
    console.clear()
    console.log( evt.target.name )
    }
  }
<form name="Test">
  <button type="button" name="button1" class=".btn">Goodbye World</button>
  <button type="button" name="button2" class=".btn">Hello World</button>
  <input type="text" name="textField" value="" placeholder="TEXT NEEDS UPDATING">
</form>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!