What topic is this task focused on?

Set the body of a single function f so that the value of i2.value becomes synchronized with i1.value , that is, it must be equal to i1.value and change further when i1.value changes.

i1 and i2 - input elements.

Restriction1: do not use global variables
i1.id : i1.id and i2.id undefined and cannot be defined.
Restriction 3: you can not modify the properties of i1 and i2, except for the value and properties responsible for the events ( onChange , etc.).

 function f(i1,i2) // i1,i2 - input-элементы {} 
  • one
    on DOM events and closures - Igor

3 answers 3

I haven’t studied ES6 yet, so maybe my version will suit you:

 'use strict'; function f(i1, i2) { function sync(event) { i2.value = event.target.value; } i1.addEventListener('input', sync); } f(document.getElementsByTagName('input')[0], document.getElementsByTagName('input')[1]); 
  <input> <input> 

  • According to the task you only have one-way synchronization (i2 is equal to i1). so I did.
  • Synchronization from the second field to the first does not work. - Qwertiy
  • one
    @Qwertiy Hello! This was not required on the instructions. - Alexander Kazakov
  • Um ... Only I understand synchronization as a bidirectional connection? - Qwertiy

cannot modify properties of i1 and i2, except for value and properties responsible for events

Well, still written in this phrase. It is necessary to subscribe to events and modify value in their handler.

For example, with browser support for ES6, you can do this:

 function f(i1, i2) { const i = [i1, i2]; for (let q=0; q<2; ++q) { i[q].addEventListener('input', e => i[q^1].value = e.target.value); } } f(document.querySelector('input'), document.querySelector('input+input')); 
 <input> <input> 

  • Is it possible to implement this without ES6? I'm just learning, and I don't quite understand how to do it ( - Ruslan
  • @Ruslan See my answer. - Alexander Kazakov
  • You can f (i1, i2) -> f (... args). then we get rid of const i = [i1, i2]; - YozhEzhi
  • In this particular problem, 2 addEventListener calls would be much more readable - vp_arth

 var inputs = document.querySelectorAll('input') for (let input of inputs) { input.oninput = function(e) { var event = new CustomEvent('sync', { detail: input.value }) for (let mInput of inputs) { mInput.dispatchEvent(event) } } input.addEventListener('sync', function(e) { input.value = e.detail }) } 
 <input type="text"> <input type="text">