Как отключить некоторые флажки на основе установленного переключателя? - PullRequest
0 голосов
/ 03 августа 2020

Как сказано в заголовке, я хочу отключить некоторые флажки на основе установленного переключателя.

Например, я нажимаю первый переключатель id="pz1", а затем отключаю флажки, которые id то же самое, что указано в массиве thisToppings. У каждой радиокнопки есть соответствующие флажки, которые нужно отключить.

Пока что я могу отключить только первые четыре флажка из шести в первом переключателе. В то время как другой переключатель, функция отключения флажков не работает. И каждый раз, когда я нажимаю любую из переключателей, появляется сообщение об ошибке, что id в xxToppings[i].id не определено.

Я хочу завершить это в vanilla Javascript, любая помощь приветствуется. Спасибо.

скрипт. js

const pzPrice = form.elements.pz;
const toppingsPrice = form.elements.topping;

    pzPrice[0].onclick = () => {
    const thisToppings = [
        { id: "tp0" },
        { id: "tp1" },
        { id: "tp2" },
        { id: "tp3" },
        { id: "tp7" },
        { id: "tp10" }
    ];

    for (let i = 0; i < toppingsPrice.length; i++) {
        if (toppingsPrice[i].id === thisToppings[i].id) {
            toppingsPrice[i].disabled = true;
        } else toppingsPrice[i].disabled = false;
    }
};

pzPrice[1].onclick = () => {
    const thisOtherToppings = [
        { id: "tp1" },
        { id: "tp2" },
        { id: "tp3" },
        { id: "tp4" },
        { id: "tp5" },
        { id: "tp6" },
        { id: "tp8" },
        { id: "tp10" }
    ]

    for (let i = 0; i < toppingsPrice.length; i++) {
        if (toppingsPrice[i].id === thisOtherToppings[i].id) {
            toppingsPrice[i].disabled = true;
        } else toppingsPrice[i].disabled = false;
    }
};

pzPrice[2].onclick = () => {
    const theOtherToppings = [
        { id: "tp1" },
        { id: "tp2" },
        { id: "tp3" },
        { id: "tp7" },
        { id: "tp8" },
        { id: "tp9" },
        { id: "tp10" },
        { id: "tp11" }
    ]

    for (let i = 0; i < toppingsPrice.length; i++) {
        if (toppingsPrice[i].id == theOtherToppings[i].id) {
            toppingsPrice[i].disabled = true;
        } else toppingsPrice[i].disabled = false;
    }
};

индекс. html

<form name="demo">
<section class="radio">
            <div class="container">
                <input type="radio" id="pz1" name="pz" value=8>
            </div>
            <div class="container">
                <input type="radio" id="pz2" name="pz" value=10>
            </div>
            <div class="container">
                <input type="radio" id="pz3" name="pz" value=12>
            </div>
</section>
<section class="choices">
            <div class="veggies">
                <div class="input">
                    <input type="checkbox" id="tp0" name="topping" value=1>
                    <input type="checkbox" id="tp1" name="topping" value=1>
                    <input type="checkbox" id="tp2" name="topping" value=1>
                    <input type="checkbox" id="tp3" name="topping" value=1>
                </div>
            </div>
            <div class="seafood">
                <div class="input">
                    <input type="checkbox" id="tp4" name="topping" value=2>
                    <input type="checkbox" id="tp5" name="topping" value=2>
                    <input type="checkbox" id="tp6" name="topping" value=2>
                    <input type="checkbox" id="tp7" name="topping" value=2>
                </div>
            </div>
            <div class="meat">
                <div class="input">
                    <input type="checkbox" id="tp8" name="topping" value=1>
                    <input type="checkbox" id="tp9" name="topping" value=1>
                    <input type="checkbox" id="tp10" name="topping" value=1>
                    <input type="checkbox" id="tp11" name="topping" value=1>
                </div>
            </div>
        </section>
</form>

1 Ответ

0 голосов
/ 04 августа 2020

Вот способ сделать то, что вы предлагаете, который использует делегирование событий и лучше соответствует принципу «Не повторяйтесь».

(см. Комментарии в коде для дальнейшего объяснения.)

// Identifies DOM elements
const
  form = document.querySelector("form"),
  toppingPrices = form.elements.topping;

// Calls `switchToppings` when something on the form is clicked
form.addEventListener("click", switchToppings);

// Listeners can automatically access their triggering events
function switchToppings(event){
  let list;
  const clickedThing = event.target; // `.target` property is useful
  if(clickedThing.name != "pz"){ return; } // Ignores uninteresting clicks

  // Selects list based on which radio was clicked
  if(clickedThing.id == "pz1"){ list = "tp0,tp1,tp2,tp3,tp7,tp10".split(","); }
  else if(clickedThing.id == "pz2"){ list = "tp1,tp2,tp3,tp4,tp5,tp6,tp8,tp10".split(","); }
  else if(clickedThing.id == "pz3"){ list = "tp1,tp2,tp3,tp7,tp8,tp9,tp10,tp11".split(","); }
  else{ console.log("no list found for this radio button"); return; }

  // Enables all checkboxes
  Array.from(toppingPrices).forEach(el => el.removeAttribute("disabled"));

  const
    // Collects checkboxes whose `id`s are found in the list
    disableMe = Array.from(toppingPrices).filter(el => list.includes(el.id));
  // Disables the collected checkboxes
  disableMe.forEach(el => el.setAttribute("disabled", ""));
};
<form name="demo">
  <section class="radio">
    <div class="container">
      <input type="radio" id="pz1" name="pz" value=8>
    </div>
    <div class="container">
      <input type="radio" id="pz2" name="pz" value=10>
    </div>
    <div class="container">
      <input type="radio" id="pz3" name="pz" value=12>
    </div>
  </section>
  <section class="choices">
    <div class="veggies">
      <div class="input">
        <input type="checkbox" id="tp0" name="topping" value=1>0
        <input type="checkbox" id="tp1" name="topping" value=1>1
        <input type="checkbox" id="tp2" name="topping" value=1>2
        <input type="checkbox" id="tp3" name="topping" value=1>3
      </div>
    </div>
    <div class="seafood">
      <div class="input">
        <input type="checkbox" id="tp4" name="topping" value=2>4
        <input type="checkbox" id="tp5" name="topping" value=2>5
        <input type="checkbox" id="tp6" name="topping" value=2>6
        <input type="checkbox" id="tp7" name="topping" value=2>7
      </div>
    </div>
    <div class="meat">
      <div class="input">
        <input type="checkbox" id="tp8"  name="topping" value=1>8
        <input type="checkbox" id="tp9"  name="topping" value=1>9
        <input type="checkbox" id="tp10" name="topping" value=1>10
        <input type="checkbox" id="tp11" name="topping" value=1>11
      </div>
    </div>
  </section>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...