简体   繁体   中英

How to take the inputs from a parent div and take realtime values from them with Javascript

I encountered a problem that I don't really know how to approach. For example, I will have a div to which I will apply a data attribute

<div class="filter-content" data-filters>
    <div class="filter-attributes">
      <input type="checkbox" name="S1P3">
      <input type="checkbox" name="S1P4">
      <input type="checkbox" name="S1P5">
      <input type="checkbox" name="S1P6">
      <input type="checkbox" name="S1P7">
      <input type="checkbox" name="S1P8">
      <input type="checkbox" name="S1P9">
      <input type="checkbox" name="S1P10">
      <input type="checkbox" name="S1P2">
      <input type="checkbox" name="S1P12">
      <input type="checkbox" name="SP52">
      <input type="checkbox" name="CI">
      <input type="radio" name="CI2">
      <input type="radio" name="CI3">
      <select name="test">
        <option value="test">Test</option>
        <option value="test1">Test1</option>
        <option value="test2">Test2</option>
        <option value="test3">Test3</option>
        <option value="test4">Test4</option>
        <option value="test5">Test5</option>
        <option value="test6">Test6</option>
        <option value="test7">Test7</option>
      </select>
    </div>
  </div>
/**
     * @return {void}
     */
    getFiltersData: function() {
      let filtersInputs = document.querySelector('[data-filters]');
      console.log(filtersInputs)
      
    },

But I don't know how I could add an event on each input / select there and take the value when it changes Is there a simple idea?

I guess you need something like this:

let filtersInputs = document
  .querySelector('[data-filters]')
  .querySelectorAll('input, select');

filtersInputs.forEach((input)=>{
  input.addEventListener('change', (e)=>{
    console.log(e.target.value);
  })
})

Note that you're not assigning any values in your HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM