DEV Community

Frank Wisniewski
Frank Wisniewski

Posted on

One handler for all Inputs

minimalistic vanilla.js to handle Input Elements:

    <!DOCTYPE html>
    <html lang="de">
    <head>
      <meta charset="UTF-8">
      <title>Handle Inputs</title>
    </head>
    <body>
      <h1>One Handler for all Inputs</h1>
      <label>normal input:</label>
      <input type="text" data-source=myInput>
      <p>you typed <b><span data-target=myInput></span></b></p>
      <label>filtered Input:</label>
      <input type="text" data-source=myFilteredInput data-filter=onlyabc placeholder="allowed chars = abc">
      <p>you typed <b><span data-target=myFilteredInput></span></b></p>
      <label>filtered Input and calc:</label>
      <input type="text" data-source=myFilteredAndCalcInput data-filter=inputInt data-func=inputToHex placeholder="only numbers from 0 to 9" value=16384>
      <p>the hexvalue is #<b><span data-target=myFilteredAndCalcInput></span></b></p>
      <h2>it works also for range-sliders: <span data-target=weight></span></h2>
      <input data-source=weight type=range min=1 max=10 value=5>
      <h2>or selects:</h2>
      <select  data-source=myCar data-func=carSelect>
        <option value="Volvo">Volvo</option>
        <option value="Saab">Saab</option>
        <option value="Mercedes">Mercedes</option>
        <option value="Audi">Audi</option>
      </select>
      <p>the price of the selected car: <b><span data-target=myCar></span> €</b></p>
    <script>
      "use strict"

      const myCars = {
          "Volvo" : 10000,
          "Saab"  : 11000,
          "Mercedes"  : 12000,
          "Audi"  : 13000
        }

      let d = d => document.querySelector(d)

      var onlyabc = t => t.replace(/[^abc]/g, '')
      var inputInt = t => t.replace(/[^0-9]/g, '')
      var inputToHex = t => new Number(t).toString(16)
      var carSelect = el => myCars[el] 

      const watchInput = function(callback) {
        let handleValues = (el) => {
          if (el.dataset.filter)
            el.value = window[el.dataset.filter](el.value)
          if (el.dataset.source) {
            let dataInput = el.dataset.input
            let dataValue = el.value
            if (d(`[data-target="${el.dataset.source}"]`)) {
              if (el.dataset.func)
                dataValue = window[el.dataset.func](dataValue)
              d(`[data-target="${el.dataset.source}"]`).innerText = dataValue
            }
          }
          if (callback) callback()
        }

        document.querySelectorAll(`[data-source]`)
          .forEach(el => handleValues(el)
          )

        d('body').addEventListener('input', e => handleValues (e.target))
      }
      watchInput()
    </script>      

    </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

you can view it in action and
test it: codepen

Discussion (0)