0

Пытаюсь вывести Атрибуты группы категорий, не могу понять почему не хочет подтягивать id группы, выдает api/v2/attributes?groups_id=undefined, но если undefined меняю на 1 все атрибуты видны. По коду вижу что присваивается группе ID но при нажатии на группу он не передается в группу.

<div class="row">
  <span class="col-md-2 group-items" onclick="changeGroups(this)" data-gr="1" data-subcat="false">Основные </span>
  <div class="row">

    <div class="col-mg-12">
      <fieldset id="group_attributes"></fieldset>
    </div>

  </div>
  </div>

//Вывод Групп

function renderSubFields(fields) {

  const specifi = document.getElementById('category_groups');
  document.getElementById('category_groups').innerHTML = '';

  if (fields[0].data && fields[1].success) {

    let typeElement = '';
    fields[0].data.forEach(parameter => {
      if (parameter.name === "varchar") typeElement = 'text';
      if (parameter.id === "int") typeElement = 'text';

      let inputFields = `<div class = "row">
      <span  class="col-md-2 group-items" onclick = "changeGroups(this)" data-gr = "${parameter.id}" data-subcat="false">${parameter.name} </span>
      <div class = "row">

        <div class = "col-mg-12">
          <fieldset id='group_attributes'></fieldset>
        </div>

      </div>
      </div>`;
      specifi.insertAdjacentHTML('beforeend', inputFields);
    })
  }

  }

//Вывод атрибутов групп

function renderSubField(field) {

    const specifications = document.getElementById('group_attributes');
    document.getElementById('group_attributes').innerHTML = '';

    if (field[0].data && field[1].success) {

      let typeElement = '';
      field[0].data.forEach(parameter => {
        if (parameter.type === "text" || parameter.type === "text_select") typeElement = 'input';
        if (parameter.type === "select") typeElement = 'select';
        if (parameter.type === "checkbox") typeElement = 'div';

        const element = document.createElement(typeElement);
        element.id = parameter.id;
        if (parameter.type !== 'checkbox') {
          element.className = 'form-control col mb-3 col-md-3';
        }

        if (parameter.type === 'input' || parameter.type === "text_select") element.type = "text";

        let selElement = document.createElement('span');

        if (parameter.options.length > 0 && parameter.type === 'text_select') {

          selElement = document.createElement('select');
          selElement.className = 'form-control col mb-3 col-md-3';

          parameter.options.forEach(opt => {
            selElement.insertAdjacentHTML("beforeend", `<option value = "${opt.id}">${opt.name}</option>`);
          });
        }

        if (parameter.options.length > 0 && parameter.type === 'select') {
          parameter.options.forEach(opt => {
            element.insertAdjacentHTML("beforeend", `<option value = "${opt.id}">${opt.name}</option>`);
          })
        }
        if (parameter.options.length > 0 && parameter.type === 'checkbox') {
          parameter.options.forEach(opt => {
            element.insertAdjacentHTML("beforeend", `<div><span><input id="${opt.id}" type="checkbox" style="opacity:1;"></span><span style="margin-left:40px;">${opt.name}</span></div><br />`);
          })
        }

        let inputField = `<div class = "row"><span  class="col-md-2">${parameter.name}: </span>${element.outerHTML}&nbsp;${selElement.outerHTML}</div>`;
        specifications.insertAdjacentHTML('beforeend', inputField);
      })
    }
  }

  var groupsId = '';

  function changeGroups() {
    $(this).click(function () {
      groupsId = $(this).attr('data-gr');

      fetch(`${url}/attributes?groups_id=${groupsId}`)
        .then(response => {
          if (response.status === 200) {
            return response.json();
          } else console.error(`Status code: ${response.status}`)
        })
        .then(async data => {
          renderSubField(await data)
        })
        .catch(e => console.log(e));
    });
  }

4
  • Вы что-то непонятное делаете... Зачем в обработчике клика changeGroups вы вешаете обработчик клика? 29 июл 2021 в 6:30
  • Не сразу загружать атрибуты группы а при клике на группу. То есть выбирается Категория относительно ее загружаются Группы при клике на группу загружаются Атрибуты. 29 июл 2021 в 8:13
  • 1
    Понятно, а зачем в changeGroups вешаете обрабочтик клика на $(this)? 29 июл 2021 в 14:38
  • Думал на клик сделать, разобрался, как ниже приложу, посмотрел логика кривая, нужно общий API с Групп и Атрибутов переделать вы выводить все вместе, так криво получилось 29 июл 2021 в 21:24

1 ответ 1

1

Комментатор выше был прав вся ошибка была в this, решил таким методом

  var groupsId = '';

  function changeGroups(elem) {
    
      groupsId = $(elem).attr('data-gr');

      fetch(`${url}/attributes?groups_id=${groupsId}`)
        .then(response => {
          if (response.status === 200) {
            return response.json();
          } else console.error(`Status code: ${response.status}`)
        })
        .then(async data => {
          renderSubField(await data)
        })
        .catch(e => console.log(e));
  }

Ваш ответ

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

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