Search code examples
javascriptjavascript-databinding

JavaScript Vanilla Two Way Binding


I have found this very short yet handy two way binding code written in pure JavaScript. The data binding works fine, but what I want is to take the value from the first input and multiply it by a desired number and bind the outcome to the next input. I will appreciate any kind of help. This is my HTML Code:

<input class="age" type="number">
<input class="age" type="number">

and the JavaScript Code:

    var $scope = {};
(function () {
    var bindClasses = ["age"];
    var attachEvent = function (classNames) {
        classNames.forEach(function (className) {
            var elements = document.getElementsByClassName(className);
            for (var index in elements) {
                elements[index].onkeyup = function () {
                    for (var index in elements) {
                        elements[index].value = this.value;
                    }
                }
            }
            Object.defineProperty($scope, className, {
                set: function (newValue) {
                    for (var index in elements) {
                        elements[index].value = newValue;
                    }
                }
            });
        });
    };
    attachEvent(bindClasses);
})();

Solution

  • If the desired results is take first input value, do something with it, put it to second input then why so serious?

    (function () {
      var bindClasses = ["age"];
      var attachEvent = function (classNames) {
        classNames.forEach( function( className ) {
          var els = document.getElementsByClassName( className ),
              from, to;
          if ( 2 > els.length ) {
            return;
          }
          from = els[0];
          to   = els[els.length - 1];
    
          from.addEventListener( 'keyup', function() {
            var v = this.value;
            // Do whatever you want with that value
            // Then assign it to last el
            if ( isNaN( v ) ) {
              return;
            }
            v = v / 2;
            to.value = v;
          });
        });
      };
      attachEvent(bindClasses);
    })();