0

Реализую фильт. При 8+ активных checkbox появляется поле поиска, а активные checkbox поднимаются вверх.

Подскажите, пожалуйста, как реализовать функционал фильтра?

У меня не выходит разобраться с двумя моментами:

  1. При клике на checkbox хочу сделать чтобы добалялось/убиралось значение в счетчике(сейчас только добавляется);
  2. Если мы кликаем по элементу сheckbox он поднимается в самый верх списка, если галку убираем соответственно перемещается на прежнее место.

window.onload = function() {
  let clickDiv = document.getElementById("click-div");
  clickDiv.onclick = incrementClick;

  let resetBtn = document.getElementById("reset-button");
  resetBtn.onclick = resetCounter;
}

var counterVal = 0;

incrementClick = function() {
  updateDisplay(++counterVal);
}


function resetCounter() {
  counterVal = 0;
  updateDisplay(counterVal);
}

function updateDisplay(val) {
  document.getElementById("counter-label").innerHTML = val;
  if (counterVal >= 8) {
    document.getElementById("search_id").style.display = "block";
  } else if (counterVal <= 8) {
    document.getElementById("search_id").style.display = "none";
  }
}
  .search_id {
  display: none;
}

#click-div input {
  display: block;
}

#click-div span {
  display: inline-block; 
}
<h3>
  <center>JavaScript Click Counter</center>
</h3>
<div>
  <input id="search_id" type="поиск">
  <center>
    <h3 id="counter-label">0</h3>
  </center>
</div>
<center>
  <div>
    <div id="click-div">
      <input type="checkbox">A</input>
      <input type="checkbox">B</input>
      <input type="checkbox">C</input>
      <input type="checkbox">D</input>
      <input type="checkbox">E</input>
      <input type="checkbox">T</input>
      <input type="checkbox">Y</input>
      <input type="checkbox">U</input>
      <input type="checkbox">I</input>
    </div>
    <button id="reset-button">Reset</button>
  </div>
</center>

2 ответа 2

0

Или такой вот вариант:

((w, d) => {
  class Filter {
    filterBox = d.getElementById('click-div');

    checkAll = [];
    allow = [];
    disallow = [];

    counterNode;
    searchNode

    constructor(idRoot) {
      this.filterBox = d.getElementById(idRoot);
      if (!this.filterBox)
        throw new Error("Не найдено... Ошибка, ошибка, ошибка... o_O");

      this.counterNode = d.getElementById('counter-label');
      this.searchNode = d.getElementById('search_id');
      this
        .setEventCheck()
        .setEventReset();
    }

    setEventCheck() {
      this.filterBox.querySelectorAll('input').forEach((el, key) => {
        let checkEl = { initRange: key, node: el };

        this.checkAll.push(checkEl);
        this.toggleFilterItem(checkEl);
        el.onchange = this.toggleFilterItem.bind(this, checkEl, false);
      });

      this.rangeFilterItem();
      return this;
    }

    setEventReset() {
      this.filterBox.onreset = () => {
        this.checkAll.forEach(checkEl => {
          this.toggleFilterItem(checkEl, true);
        });
      };
      return this;
    }

    toggleFilterItem(checkEl, off = false) {
      if (checkEl.node.checked && !off) {
        delete this.disallow[checkEl.initRange];
        this.allow[checkEl.initRange] = checkEl.node;
      } else {
        delete this.allow[checkEl.initRange];
        this.disallow[checkEl.initRange] = checkEl.node;
      }

      this.rangeFilterItem();
    }

    toggleSearch(show) {
      if (show)
        this.searchNode.classList.remove('search_hide');
      else
        this.searchNode.classList.add('search_hide');
    }

    changeCountAllow(count) {
      this.counterNode.innerText = count;

      return this;
    }

    rangeFilterItem() {
      let count = 0;

      this.allow.forEach(el => {
        el.parentElement.style.order = ++count;
      });

      this.changeCountAllow(count);
      this.toggleSearch(count == this.checkAll.length);

      this.disallow.forEach(el => {
        el.parentElement.style.order = ++count;
      });

      return this;
    }
  }

  d.addEventListener('DOMContentLoaded', () => {
    const filter = new Filter('click-div');

  });
})(window, document);
  .search_hide {
  display: none;
}

#click-div span {
  display: inline-block;
}

#click-div {
  display: flex;
  flex-direction: column;
}
<h3>
<center>JavaScript Click Counter</center>
  </h3>
  <div>
<input id="search_id" class="search_hide" type="поиск">
<center>
  <h3 id="counter-label">0</h3>
</center>
  </div>
  <center>
<div>
  <form id="click-div">
    <div><input type="checkbox" data-position="">A</div>
    <div><input type="checkbox" data-position="">B</div>
    <div><input type="checkbox" data-position="">C</div>
    <div><input type="checkbox" data-position="">D</div>
    <div><input type="checkbox" data-position="">E</div>
    <div><input type="checkbox" data-position="">T</div>
    <div><input type="checkbox" data-position="">Y</div>
    <div><input type="checkbox" data-position="">U</div>
    <div><input type="checkbox" data-position="">I</div>
  </form>
<button id="reset-button" form="click-div" type="reset">Reset</button>
</div>
  </center>

1
  • Спасибо, ОГРОМНОЕ)) Работает как нужно. Сейчас попробую внедрить это в 1с битрикс)
    – Dmitry
    23 авг 2022 в 14:32
0
  1. Считать надо не клики на чекбокс, а отмеченные чекбоксы.

  2. Можно сделать следующим образом. (Кстати, буду признателен, если кто-то сможет объяснить, почему вторичная сортировка инпутов по id работает в Firefox, но не работает в Chrome.)

clickHandler = function(e) {
    const target = e.target;
    const inputIndex = inputs.indexOf(target);
    counterVal = 0;
    inputs.forEach(inp => counterVal += inp.checked === true); //считаем чекнутые инпуты
    inputs.sort((a, b) => b.id < a.id).sort((a, b) => b.checked - a.checked);
    inputs.forEach(function(inp){
      let copyInp = inp.cloneNode(); //копия инпута
      let text = inp.nextSibling.textContent; // копия текста после инпута
      allInputs.insertAdjacentElement('beforeend', copyInp);
      allInputs.insertAdjacentText('beforeend', text);
      inp.nextSibling.remove();
      inp.remove();
      inputs = Array.from(allInputs.querySelectorAll("input"));
      inputs.forEach(inp => inp.addEventListener('click', clickHandler));
    });
  updateDisplay(counterVal);
}


function resetCounter() {
  counterVal = 0;
  updateDisplay(counterVal);
}

function updateDisplay(val) {
  document.getElementById("counter-label").innerHTML = val;
  if (counterVal >= 8) {
    document.getElementById("search_id").style.display = "block";
  } else if (counterVal <= 8) {
    document.getElementById("search_id").style.display = "none";
  }
}

let counterVal = 0;
const allInputs = document.getElementById("all-inputs");
let inputs = Array.from(allInputs.querySelectorAll("input"));
inputs.forEach(inp => inp.addEventListener('click', clickHandler));
let resetBtn = document.getElementById("reset-button");
resetBtn.onclick = resetCounter;
.search_id {
            display: none;
            }

            #all-inputs input {
            display: block;
            }

            #all-inputs span {
            display: inline-block;
            }
<h3>
            <center>JavaScript Click Counter</center>
          </h3>
          <div>
            <input id="search_id" type="поиск">
            <center>
              <h3 id="counter-label">0</h3>
            </center>
          </div>
          <center>
            <div>
              <div id="all-inputs">
                  <input id='A' type="checkbox">A</input>
                  <input id='B' type="checkbox">B</input>
                  <input id='C' type="checkbox">C</input>
                  <input id='D' type="checkbox">D</input>
                  <input id='E' type="checkbox">E</input>
                  <input id='I' type="checkbox">I</input>
                  <input id='T' type="checkbox">T</input>
                  <input id='U' type="checkbox">U</input>
                  <input id='Y' type="checkbox">Y</input>
                </div>
                
              <button id="reset-button">Reset</button>
            </div>
          </center>
          

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.