Home > Net >  Multiple buttons change the value of a single input text field of in a HTML form using JS
Multiple buttons change the value of a single input text field of in a HTML form using JS

Time:07-02

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" >
    <input type="button" name="button2" value="Hello World" >

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

CodePudding user response:

  • 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 useinstead of```.

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" >
    <input type="button" name="button2" value="Hello World" >

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

CodePudding user response:

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"  id="btn1">
    <input type="button" name="button2" value="Hello World" id="btn2" >

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

CodePudding user response:

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" >Goodbye World</button>
  <button type="button" name="button2" >Hello World</button>
  <input type="text" name="textField" value="" placeholder="TEXT NEEDS UPDATING">
</form>

  • Related