динамическое добавление данных javascript - PullRequest
0 голосов
/ 14 июля 2020

У меня проблема с добавлением события к элементу, у меня всего 2 элемента и 2 события, но мой второй элемент вызывает событие, которое не связано с ним.

У меня есть опции и опции Faturamento ( - это список элементов)

, но когда я нажимаю на один из дочерних элементов моих параметров

, я вызываю событие my element opition click

проблема в фрагменте:

const data = [
  {
    id: 1,
    name: "SIMPLES NACIONAL – MEI",
    funcionarioIncrease: 49.99,
    maxFuncionario: 1,
    socioIncrease: 0,
    maxSocio: 5,
    FATURAMENTO: [
      {
        id: 1,
        name: "ATÉ 30.000,00",
        value: 49.99,
      },
      {
        id: 2,
        name: "De 30.001,00 a 50.000,00 ",
        value: 99.99,
      },
    ],
  },
  {
    id: 2,
    name: "SIMPLES NACIONAL – SERVIÇOS",
    funcionarioIncrease: 25,
    maxFuncionario: 3,
    socioIncrease: 25,
    maxSocio: 5,
    FATURAMENTO: [
      {
        id: 1,
        name: "ATÉ 50.000,00",
        value: 149.99,
      },
      {
        id: 2,
        name: "De 40.001,00 a 50.000,00 ",
        value: 199.99,
      },
    ],
  },
];

function createInput(id) {
  let inputRadio = document.createElement("input");

  if (id) {
    inputRadio.id = id;
    inputRadio.name = "category";
    inputRadio.type = "radio";
    inputRadio.value = id;
    inputRadio.classList.add("radio");
    return inputRadio;
  }
  return null;
}

function createFaturamento() {
  let container = document.querySelector(".faturamento-container");
  let selectedFaturamento = document.querySelector(".faturamentoSelected");

  data.forEach((value) => {
    if (value.id == 1) {
      value.FATURAMENTO.forEach((faturamento) => {
        let optionDiv = document.createElement("div");
        optionDiv.classList.add("options-faturamento");
        container.append(optionDiv);
        let input = createInput(faturamento.id);
        if (!input) {
          return null;
        }
        optionDiv.append(input);
        let label = document.createElement("label");
        label.htmlFor = value.id;
        label.innerHTML = faturamento.name;
        optionDiv.append(label);
        if (faturamento.id == 1) {
          selectedFaturamento.innerHTML = faturamento.name;
          selectedFaturamento.setAttribute("data-value", faturamento.id);
        }
      });
    }
  });
}
function createModeOptions() {
  let container = document.querySelector(".options-container");
  let selectedMode = document.querySelector(".selected");
  data.forEach((value) => {
    let optionDiv = document.createElement("div");
    optionDiv.classList.add("options-services");
    container.append(optionDiv);
    let input = createInput(value.id);
    if (!input) {
      return null;
    }
    optionDiv.append(input);
    var label = document.createElement("label");
    label.htmlFor = value.id;
    label.innerHTML = value.name;
    optionDiv.append(label);
    if (value.id == 1) {
      selectedMode.innerHTML = value.name;
      selectedMode.setAttribute("data-value", value.id);
    }
  });
}

function initalize() {
  //variables modes
  let container = document.querySelector(".options-container");
  let selectedMode = document.querySelector(".selected");
  let options = document.querySelectorAll(".options-services");
  //variables faturamento
  let selectedFaturamento = document.querySelector(".faturamentoSelected");
  let faturamentoContainer = document.querySelector(".faturamento-container");
  let optionsFaturamento = document.querySelectorAll(".options-faturamento");
  //events
  selectedMode.addEventListener("click", () => {
    faturamentoContainer.classList.remove("active");
    container.classList.toggle("active");
  });

  selectedFaturamento.addEventListener("click", () => {
    faturamentoContainer.classList.toggle("active");
  });

  options.forEach((o) => {
    o.addEventListener("click", () => {
      let input = o.querySelector("input").id;
      console.log(o);
      console.log(o.querySelector("label"));
      selectedMode.innerHTML = o.querySelector("label").innerHTML;
      selectedMode.setAttribute("data-value", input);
      container.classList.remove("active");
    });
  });

  optionsFaturamento.forEach((o) => {
    o.addEventListener("click", () => {
      let input = o.querySelector("input").id;
      selectedFaturamento.innerHTML = o.querySelector("label").innerHTML;
      selectedFaturamento.setAttribute("data-value", input);
      faturamentoContainer.classList.remove("active");
    });
  });

  //call functions
}
createModeOptions();
createFaturamento();
initalize();
/* custom select faturamento */
.option-faturamento {
  border-radius: 8px;
}
.faturamento-box {
  display: flex;
  width: 100%;
  max-height: 50px;
  flex-direction: column;
  position: relative;
}

.faturamento-container {
  padding: 0;
  background: #fff;
  color: #000;
  max-height: 0;
  width: 100%;
  opacity: 0;
  transition: all 0.4s;
  border: 1px solid #dadada;
  border-radius: 8px;
  position: absolute;
  overflow: hidden;
  order: 1;
  top: 120%;
}
.faturamento-container::after {
  position: absolute;
  display: block;
  content: "";
  bottom: 100%;
  right: 25px;
  width: 7px;
  height: 7px;
  margin-bottom: -3px;
  border-top: 1px solid #dadada;
  border-left: 1px solid #dadada;
  background: #fff;
  transform: rotate(45deg);
  transition: all 0.4s ease-in-out;
}
.faturamentoSelected {
  width: 100%;
  font-size: 1rem;
  outline: none;
  border: 1px solid #ffb24f;
  border-radius: 5px;
  padding: 1rem 0.7rem;
  font-family: "Poppins";
  background: #00416a;
  color: #ffb24f;
  transition: 0.1s ease-out;
  position: relative;
  order: 0;
}
.faturamentoSelected::before {
  background: none;
  border: 1px solid #ffb24f;
  content: "";
  display: block;
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  pointer-events: none;
}
.faturamentoSelected::after {
  position: absolute;
  display: block;
  content: "";
  width: 10px;
  height: 10px;
  top: 50%;
  right: 25px;
  border-bottom: 1px solid #dadada;
  border-right: 1px solid #dadada;
  transform: rotate(45deg) translateY(-50%);
  transition: all 0.4s ease-in-out;
  transform-origin: 50% 0;
  transition: all 0.4s;
}

.faturamento-container.active {
  max-height: 240px;
  opacity: 1;
  padding: 10px 0;
  overflow: visible;
  z-index: 999;
}

.faturamento-box .faturamento-container.active + .faturamentoSelected::after {
  margin-top: 3px;
  transform: rotate(-135deg) translateY(-50%);
}

.faturamento-container::-webkit-scrollbar {
  width: 8px;
  background: #fff;
  border-radius: 0 8px 8px 0;
}
.faturamento-container::-webkit-scrollbar-thumb {
  background: #dadada;
  border-radius: 0 8px 8px 0;
}

.faturamento-box .option-faturamento,
.faturamentoSelected {
  padding: 12px 24px;
  cursor: pointer;
}

.faturamento-box label {
  cursor: pointer;
  font-family: "Poppins";
  color: orange;
}

.faturamento-box label:hover {
  color: orange;
}
.faturamento-box .options-faturamento .radio {
  display: none;
}

.options-faturamento {
  padding: 12px 24px;
  cursor: pointer;
}
/* custom select faturamento */
/*custom select services2 */
.option {
  border-radius: 8px;
}
.select-box {
  display: flex;
  width: 100%;
  max-height: 50px;
  flex-direction: column;
  position: relative;
}

.select-box .options-container {
  padding: 0;
  background: #fff;
  color: #000;
  max-height: 0;
  width: 100%;
  opacity: 0;
  transition: all 0.4s;
  border: 1px solid #dadada;
  border-radius: 8px;
  position: absolute;
  overflow: hidden;
  order: 1;
  top: 120%;
}
.select-box .options-container::after {
  position: absolute;
  display: block;
  content: "";
  bottom: 100%;
  right: 25px;
  width: 7px;
  height: 7px;
  margin-bottom: -3px;
  border-top: 1px solid #dadada;
  border-left: 1px solid #dadada;
  background: #fff;
  transform: rotate(45deg);
  transition: all 0.4s ease-in-out;
}
.selected {
  width: 100%;
  font-size: 1rem;
  outline: none;
  border: 1px solid #ffb24f;
  border-radius: 5px;
  padding: 1rem 0.7rem;
  font-family: "Poppins";
  background: #00416a;
  color: #ffb24f;
  transition: 0.1s ease-out;
  position: relative;
  order: 0;
}
.selected::before {
  background: none;
  border: 1px solid #ffb24f;
  content: "";
  display: block;
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  pointer-events: none;
}
.selected::after {
  position: absolute;
  display: block;
  content: "";
  width: 10px;
  height: 10px;
  top: 50%;
  right: 25px;
  border-bottom: 1px solid #dadada;
  border-right: 1px solid #dadada;
  transform: rotate(45deg) translateY(-50%);
  transition: all 0.4s ease-in-out;
  transform-origin: 50% 0;
  transition: all 0.4s;
}

.select-box .options-container.active {
  max-height: 240px;
  opacity: 1;
  padding: 10px 0;
  overflow: visible;
  z-index: 999;
}

.select-box .options-container.active + .selected::after {
  margin-top: 3px;
  transform: rotate(-135deg) translateY(-50%);
}

.select-box .options-container::-webkit-scrollbar {
  width: 8px;
  background: #fff;
  border-radius: 0 8px 8px 0;
}

.select-box .options-container::-webkit-scrollbar-thumb {
  background: #dadada;
  border-radius: 0 8px 8px 0;
}

.select-box .options-services,
.selected {
  padding: 12px 24px;
  cursor: pointer;
}

.select-box label {
  cursor: pointer;
  font-family: "Poppins";
  color: orange;
}

.select-box label:hover {
  color: orange;
}
.select-box .options-services .radio {
  display: none;
}
            <div class="custom_select flex">
              <h3 class="textfield_label">
                Selecione a categoria da sua Empresa
              </h3>
              <div class="select-box">
                <div class="options-container"></div>

                <div class="selected">
                  Selecione um Tipo de Serviço
                </div>
              </div>
            </div>
                        <div id="faturamento" class="custom_select flex">
              <h3 class="textfield_label">
                Selecione o faturamento mensal da sua Empresa
              </h3>
              <div class="faturamento-box">
                <div class="faturamento-container"></div>

                <div class="faturamentoSelected">
                  Qual o faturamento mensal?
                </div>
              </div>
            </div>

введите описание изображения здесь

1 Ответ

1 голос
/ 14 июля 2020

Идентификаторы элементов должны быть уникальными. Вы используете faturamento.id в качестве идентификаторов для некоторых входов и value.id для других входов, и они имеют те же значения.

Когда вы создаете метку с помощью for="1", она будет связаны только с одним из этих входов, который может быть не тем, который вы хотите использовать.

Добавьте что-нибудь к идентификаторам, чтобы различать guish их. Я использую префикс «feat-» или «значение -».

const data = [{
    id: 1,
    name: "SIMPLES NACIONAL – MEI",
    funcionarioIncrease: 49.99,
    maxFuncionario: 1,
    socioIncrease: 0,
    maxSocio: 5,
    FATURAMENTO: [{
        id: 1,
        name: "ATÉ 30.000,00",
        value: 49.99,
      },
      {
        id: 2,
        name: "De 30.001,00 a 50.000,00 ",
        value: 99.99,
      },
    ],
  },
  {
    id: 2,
    name: "SIMPLES NACIONAL – SERVIÇOS",
    funcionarioIncrease: 25,
    maxFuncionario: 3,
    socioIncrease: 25,
    maxSocio: 5,
    FATURAMENTO: [{
        id: 1,
        name: "ATÉ 50.000,00",
        value: 149.99,
      },
      {
        id: 2,
        name: "De 40.001,00 a 50.000,00 ",
        value: 199.99,
      },
    ],
  },
];

function createInput(prefix, id) {
  let inputRadio = document.createElement("input");

  if (id) {
    inputRadio.id = prefix + "-" + id;
    inputRadio.name = "category";
    inputRadio.type = "radio";
    inputRadio.value = id;
    inputRadio.classList.add("radio");
    return inputRadio;
  }
  return null;
}

function createFaturamento() {
  let container = document.querySelector(".faturamento-container");
  let selectedFaturamento = document.querySelector(".faturamentoSelected");

  data.forEach((value) => {
    if (value.id == 1) {
      value.FATURAMENTO.forEach((faturamento) => {
        let optionDiv = document.createElement("div");
        optionDiv.classList.add("options-faturamento");
        container.append(optionDiv);
        let input = createInput("feat", faturamento.id);
        if (!input) {
          return null;
        }
        optionDiv.append(input);
        let label = document.createElement("label");
        label.htmlFor = "feat-" + faturamento.id;
        label.innerHTML = faturamento.name;
        optionDiv.append(label);
        if (faturamento.id == 1) {
          selectedFaturamento.innerHTML = faturamento.name;
          selectedFaturamento.setAttribute("data-value", faturamento.id);
        }
      });
    }
  });
}

function createModeOptions() {
  let container = document.querySelector(".options-container");
  let selectedMode = document.querySelector(".selected");
  data.forEach((value) => {
    let optionDiv = document.createElement("div");
    optionDiv.classList.add("options-services");
    container.append(optionDiv);
    let input = createInput("value", value.id);
    if (!input) {
      return null;
    }
    optionDiv.append(input);
    var label = document.createElement("label");
    label.htmlFor = "value-" + value.id;
    label.innerHTML = value.name;
    optionDiv.append(label);
    if (value.id == 1) {
      selectedMode.innerHTML = value.name;
      selectedMode.setAttribute("data-value", value.id);
    }
  });
}

function initalize() {
  //variables modes
  let container = document.querySelector(".options-container");
  let selectedMode = document.querySelector(".selected");
  let options = document.querySelectorAll(".options-services");
  //variables faturamento
  let selectedFaturamento = document.querySelector(".faturamentoSelected");
  let faturamentoContainer = document.querySelector(".faturamento-container");
  let optionsFaturamento = document.querySelectorAll(".options-faturamento");
  //events
  selectedMode.addEventListener("click", () => {
    faturamentoContainer.classList.remove("active");
    container.classList.toggle("active");
  });

  selectedFaturamento.addEventListener("click", () => {
    faturamentoContainer.classList.toggle("active");
  });

  options.forEach((o) => {
    o.addEventListener("click", () => {
      let input = o.querySelector("input").id;
      console.log(o);
      console.log(o.querySelector("label"));
      selectedMode.innerHTML = o.querySelector("label").innerHTML;
      selectedMode.setAttribute("data-value", input);
      container.classList.remove("active");
    });
  });

  optionsFaturamento.forEach((o) => {
    o.addEventListener("click", () => {
      let input = o.querySelector("input").id;
      selectedFaturamento.innerHTML = o.querySelector("label").innerHTML;
      selectedFaturamento.setAttribute("data-value", input);
      faturamentoContainer.classList.remove("active");
    });
  });

  //call functions
}
createModeOptions();
createFaturamento();
initalize();
/* custom select faturamento */

.option-faturamento {
  border-radius: 8px;
}

.faturamento-box {
  display: flex;
  width: 100%;
  max-height: 50px;
  flex-direction: column;
  position: relative;
}

.faturamento-container {
  padding: 0;
  background: #fff;
  color: #000;
  max-height: 0;
  width: 100%;
  opacity: 0;
  transition: all 0.4s;
  border: 1px solid #dadada;
  border-radius: 8px;
  position: absolute;
  overflow: hidden;
  order: 1;
  top: 120%;
}

.faturamento-container::after {
  position: absolute;
  display: block;
  content: "";
  bottom: 100%;
  right: 25px;
  width: 7px;
  height: 7px;
  margin-bottom: -3px;
  border-top: 1px solid #dadada;
  border-left: 1px solid #dadada;
  background: #fff;
  transform: rotate(45deg);
  transition: all 0.4s ease-in-out;
}

.faturamentoSelected {
  width: 100%;
  font-size: 1rem;
  outline: none;
  border: 1px solid #ffb24f;
  border-radius: 5px;
  padding: 1rem 0.7rem;
  font-family: "Poppins";
  background: #00416a;
  color: #ffb24f;
  transition: 0.1s ease-out;
  position: relative;
  order: 0;
}

.faturamentoSelected::before {
  background: none;
  border: 1px solid #ffb24f;
  content: "";
  display: block;
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  pointer-events: none;
}

.faturamentoSelected::after {
  position: absolute;
  display: block;
  content: "";
  width: 10px;
  height: 10px;
  top: 50%;
  right: 25px;
  border-bottom: 1px solid #dadada;
  border-right: 1px solid #dadada;
  transform: rotate(45deg) translateY(-50%);
  transition: all 0.4s ease-in-out;
  transform-origin: 50% 0;
  transition: all 0.4s;
}

.faturamento-container.active {
  max-height: 240px;
  opacity: 1;
  padding: 10px 0;
  overflow: visible;
  z-index: 999;
}

.faturamento-box .faturamento-container.active+.faturamentoSelected::after {
  margin-top: 3px;
  transform: rotate(-135deg) translateY(-50%);
}

.faturamento-container::-webkit-scrollbar {
  width: 8px;
  background: #fff;
  border-radius: 0 8px 8px 0;
}

.faturamento-container::-webkit-scrollbar-thumb {
  background: #dadada;
  border-radius: 0 8px 8px 0;
}

.faturamento-box .option-faturamento,
.faturamentoSelected {
  padding: 12px 24px;
  cursor: pointer;
}

.faturamento-box label {
  cursor: pointer;
  font-family: "Poppins";
  color: orange;
}

.faturamento-box label:hover {
  color: orange;
}

.faturamento-box .options-faturamento .radio {
  display: none;
}

.options-faturamento {
  padding: 12px 24px;
  cursor: pointer;
}


/* custom select faturamento */


/*custom select services2 */

.option {
  border-radius: 8px;
}

.select-box {
  display: flex;
  width: 100%;
  max-height: 50px;
  flex-direction: column;
  position: relative;
}

.select-box .options-container {
  padding: 0;
  background: #fff;
  color: #000;
  max-height: 0;
  width: 100%;
  opacity: 0;
  transition: all 0.4s;
  border: 1px solid #dadada;
  border-radius: 8px;
  position: absolute;
  overflow: hidden;
  order: 1;
  top: 120%;
}

.select-box .options-container::after {
  position: absolute;
  display: block;
  content: "";
  bottom: 100%;
  right: 25px;
  width: 7px;
  height: 7px;
  margin-bottom: -3px;
  border-top: 1px solid #dadada;
  border-left: 1px solid #dadada;
  background: #fff;
  transform: rotate(45deg);
  transition: all 0.4s ease-in-out;
}

.selected {
  width: 100%;
  font-size: 1rem;
  outline: none;
  border: 1px solid #ffb24f;
  border-radius: 5px;
  padding: 1rem 0.7rem;
  font-family: "Poppins";
  background: #00416a;
  color: #ffb24f;
  transition: 0.1s ease-out;
  position: relative;
  order: 0;
}

.selected::before {
  background: none;
  border: 1px solid #ffb24f;
  content: "";
  display: block;
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  pointer-events: none;
}

.selected::after {
  position: absolute;
  display: block;
  content: "";
  width: 10px;
  height: 10px;
  top: 50%;
  right: 25px;
  border-bottom: 1px solid #dadada;
  border-right: 1px solid #dadada;
  transform: rotate(45deg) translateY(-50%);
  transition: all 0.4s ease-in-out;
  transform-origin: 50% 0;
  transition: all 0.4s;
}

.select-box .options-container.active {
  max-height: 240px;
  opacity: 1;
  padding: 10px 0;
  overflow: visible;
  z-index: 999;
}

.select-box .options-container.active+.selected::after {
  margin-top: 3px;
  transform: rotate(-135deg) translateY(-50%);
}

.select-box .options-container::-webkit-scrollbar {
  width: 8px;
  background: #fff;
  border-radius: 0 8px 8px 0;
}

.select-box .options-container::-webkit-scrollbar-thumb {
  background: #dadada;
  border-radius: 0 8px 8px 0;
}

.select-box .options-services,
.selected {
  padding: 12px 24px;
  cursor: pointer;
}

.select-box label {
  cursor: pointer;
  font-family: "Poppins";
  color: orange;
}

.select-box label:hover {
  color: orange;
}

.select-box .options-services .radio {
  display: none;
}
<div class="custom_select flex">
  <h3 class="textfield_label">
    Selecione a categoria da sua Empresa
  </h3>
  <div class="select-box">
    <div class="options-container"></div>

    <div class="selected">
      Selecione um Tipo de Serviço
    </div>
  </div>
</div>
<div id="faturamento" class="custom_select flex">
  <h3 class="textfield_label">
    Selecione o faturamento mensal da sua Empresa
  </h3>
  <div class="faturamento-box">
    <div class="faturamento-container"></div>

    <div class="faturamentoSelected">
      Qual o faturamento mensal?
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...