0

We assume that we have the following div with the following elements:

    <div id="globalDiv" onchange="checkChange()">
        <input id="i1" type='number'/>
        <input id="i2" type='number'/>
        <input id="i3" type='number'/>
        <input id="i4" type='number'/>
        <input id="i5" type='number'/>
        <input id="i6" type='number'/>
    </div>

My question is: can I know which element of type 'input' has been modified?

Note:

I know that one solution is to place the onchange = "checkChange (this)" in each input but I see it redundant.

python38291
  • 45
  • 1
  • 6
  • I see two ways to do it. Since you have `ID` for each `input`, you can loop over all input elements using `ID` and compare their previous value with current value(note that you need to store previous value in order to compare) and second approach is to use `onchange`(preferred approach). – Ajay Dabas Jan 04 '20 at 03:13
  • @AjayDabas The truth is that it is preferable to use the onchange. Thanks for the help – python38291 Jan 04 '20 at 03:20

1 Answers1

2

You can use event.target to get the element triggered on whatever event you want, e.g. change:

const myEl = document.querySelector("#globalDiv");

myEl.addEventListener('change', function(event) {
 console.log(event.target);
})
 <div id="globalDiv">
   <input id="i1" type='number'/>
   <input id="i2" type='number'/>
   <input id="i3" type='number'/>
   <input id="i4" type='number'/>
   <input id="i5" type='number'/>
   <input id="i6" type='number'/>
</div>
dikuw
  • 1,134
  • 13
  • 22
  • The problem I see is that the event jumps in case of click and not in change. Even so, a very smart solution. Thank you !! – python38291 Jan 04 '20 at 03:22
  • (@python38291 There is no built-in "change" event on an HTML input element, so you'll have to build your own. See here: https://stackoverflow.com/questions/42427606/event-when-input-value-is-changed-by-javascript – dikuw Jan 04 '20 at 03:24