1

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>

1
  • for each class=".btn" add the.same.button.listener passing their value to a text.field.update.function called by the listener. Commented Jul 1, 2022 at 22:19

3 Answers 3

2

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', event.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>

Sign up to request clarification or add additional context in comments.

2 Comments

Sweet it worked! I had to change the e.target.value to event.target.value for it to run. Thanks for the help!
Opps! Thanks for pointing out. Chees!
2
  • 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>

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.