javascriptaddeventlistenerselectors-api

javascript - querySelectorAll with addEventListener - how to get number of interacted element and variable from variable


I have HTML:

<form name="form" ..

<input type="text" name="title1" id="title1" class="f_title" value="smth LV">
<input type="text" name="title2" id="title2" class="f_title" value="smth EN">
<input type="text" name="title3" id="title3" class="f_title" value="smth DE">

<input type="text" name="url1" id="url1" class="f_url" value="smth-lv">
<input type="text" name="url2" id="url2" class="f_url" value="smth-en">
<input type="text" name="url3" id="url3" class="f_url" value="smth-de">

If user changes input "title", i do some replacements with this value and i want to set it to the right input "url". In a "nice" way I can't get the "number" of interacted field and can't set it to the corresponding "url"... I guess i knew how to do if used for() and eval(). If i use [right] JS things like querySelectorAll and addEventListener:

let i = 1;
document.querySelectorAll('.f_title').forEach(el => {
 el.addEventListener('change', () => {

  if (typeof form.url[i] !== 'undefined') {
    ...
    form.url[i] = form.title[i].value;  // for example - if changes input "title2" - how to alert(2) and how to reference to form.url2 in this loop?
  }

 });
 i++;
});

Solution

  • You can use the second argument that the forEach callback gets: the index of the title item (either 0, 1 or 2 in your example). If you also query the collection of the url inputs, then you can use that index to access the corresponding url input.

    As example, I copy the input value in lowercase with all spaces replaced by hyphens:

    const urlInputs = document.querySelectorAll('.f_url');
    document.querySelectorAll('.f_title').forEach((el, i) => {
     el.addEventListener('input', () => {
      if (urlInputs[i]) {
        urlInputs[i].value = el.value.replaceAll(" ", "-").toLowerCase();
      }
     });
    });
    <form name="form">
    
    <input type="text" name="title1" id="title1" class="f_title" value="smth LV">
    <input type="text" name="title2" id="title2" class="f_title" value="smth EN">
    <input type="text" name="title3" id="title3" class="f_title" value="smth DE">
    
    <input type="text" name="url1" id="url1" class="f_url" value="smth-lv">
    <input type="text" name="url2" id="url2" class="f_url" value="smth-en">
    <input type="text" name="url3" id="url3" class="f_url" value="smth-de">
    
    </form>