1

I have multiple input fields. I want to get value and name of the input field by the selector getElementsByTagName while keyup. In jQuery we could do the same using this in jQuery. But I want in javascript.

Here the keyup is dynamic. And I need dynamically the value and name of input fields while on keyup in javascript.

In the below code I don't want to add a index zero, I need this to work dynamically and give the result.

   const eventClickToDisconnect = document.getElementsByTagName('input');

   eventClickToDisconnect[0].addEventListener('keyup',this.setInputValueWhileOnChange.bind(this));
sibabrat swain
  • 1,277
  • 8
  • 20
  • 3
    It doesn't seem to be related to Angular So I have removed the tag. Consider providing a [mcve] of your issue, so that we can see what you have tried, and tell you what's wrong (if any). –  Oct 09 '19 at 10:12
  • iterate over eventClickToDisconnect and instead zero index put dynamic index of your loop – vipul patel Oct 09 '19 at 10:14

1 Answers1

2

First, stop using .getElementsByTagName() as this is a 20+ year old API that returns a Live Node List, which can hurt performance. Instead, use .querySelectorAll(), which returns a static node list and is more flexible because you can pass any valid CSS selector to it (not just a tag name).

Then, you can simply iterate over the nodes in the list and bind your event handler like the following.

NOTES:

  • keyup will obviously trigger upon each keystroke. Are you sure that's what you want? Perhaps you want to wait until the user is done editing the field, in which case use change instead, which will trigger when the field loses the focus and the value has been modified.
  • .forEach() works in any modern browser on arrays and node lists, however it doesn't work in IE, if you need to be compatible with IE, you simply need to convert the node list into a formal array like this:

    Array.prototype.slice.call(document.querySelector("input"));

const eventClickToDisconnect = document.querySelectorAll('input');

// Loop over the nodes found with querySelectorAll
eventClickToDisconnect.forEach(function(element){
  element.addEventListener("keyup", setInputValueWhileOnChange);
});

function setInputValueWhileOnChange(){
  // Within this callback, you can use "this" to refer to the element that
  // the event was triggered on
  console.log(this.name, this.value);
}
Name: <input name="txtName"><br>
Age: <input name="txtAge"><br>
Fav Color: <input name="txtColor">
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71