Не удается выбрать элемент из выпадающего списка - PullRequest
0 голосов
/ 01 марта 2020

У меня есть эта форма, которая заполняется динамически, она получает данные из пользовательских категорий Wordpress и заполняет первый выпадающий список, а затем, в зависимости от выбранной вами опции, заполняет второй выпадающий список на шаге 2 https://angrimanmaderas.com/ pi c формы первый раскрывающийся список работает правильно, но когда вы переходите ко второму шагу, во втором раскрывающемся списке вы не можете выбрать элементы.

это код, с которым я работаю :

РЕДАКТИРОВАТЬ: Я думаю, что я нашел проблему:

$listItems.click(function (e) {
console.log("click on list and it has : " + $listItems.text());
e.stopPropagation();
$styledSelect.text($(this).text()).removeClass('active');
$this.val($(this).attr('rel'));
$list.hide();
if($styledSelect.hasClass('required')){
  $styledSelect.removeClass('required');
}
console.log('clickee en la list', $this.val());
if(!currCat){
  console.log('clicked list' , $this.val());
  getOptions($this.val());
}

/* alert($this.val()); Uncomment this for demonstration! */
});

$ listItems - это переменная, которая изменяется после первого выпадающего списка, я думаю, что она имеет элементы нового выпадающего списка. click не регистрирует изменение, и поэтому я не могу выбрать новые элементы в списке, я знаю, что должен использовать метод jquery .on, но не знаю, как применить его там.

jQuery(document).ready(function($) {
  // Change step button
  $('.change-step').click(function(e) {
    e.preventDefault();
    let currStep = parseInt($('.step.active').data('step'));
    let nextStep = 0;
    if ($(this).hasClass('next-step')) {
      if (validateFields(currStep)) {
        if (currStep < 4) {
          nextStep = currStep + 1;
        }
        if (currStep == 4) {
          sendForm();
        } else {
          changeSlide(nextStep, currStep);
        }
      }
    } else {
      if (currStep > 1) {
        nextStep = currStep - 1;
        changeSlide(nextStep, currStep);
      }
    }
  });

  $("input")
    .change(function() {
      if ($(this).val()) {
        $(this).removeClass('required');
      }
    });

  $('input').keyup(function() {
    if ($(this).val()) {
      $(this).removeClass('required');
    }
  });

  function changeSlide(nextStep, currStep) {
    if (nextStep == 0) {
      alert("Es 0");
    } else {
      $('.step.active').removeClass('active');
      $('.step[data-step="' + nextStep + '"]').addClass('active');
      if (nextStep > currStep) {
        $('.progress-quote ul li[data-step="' + currStep + '"]').addClass('full').removeClass('active');
        $('.progress-quote ul li[data-step="' + nextStep + '"').addClass('active');
      }
      if (nextStep == 2) {
        $('.nav-quote-form').fadeIn(300);
        $('.nav-quote-form').animate({
          'opacity': 1,
          'padding-top': 0
        }, 300);
      }
      if (nextStep == 4) {
        $('.nav-quote-form .next-step span.txt').text('Enviar presupuesto');
      } else {
        $('.nav-quote-form .next-step span.txt').text('Siguiente');
      }
    }
  }

  function validateFields(currStep) {
    if (currStep == 1) {
      if ($("select#wood_for").val()) {
        return true;
      } else {
        $('.select.wood_for div.styledSelect').addClass('required');
        return false;
      }
    } else if (currStep == 2) {
      if ($("select#wood_type").val() != "" &&
        $("input#quantity").val() != "" &&
        $("input#height").val() != "" &&
        $('input#width').val() != "" &&
        $('input#large').val() != ""
      ) {
        return true;
      } else {
        if (!$("select#wood_type").val()) {
          console.log('err');
          $('.select.wood_type div.styledSelect').addClass('required');
        }
        $(".wood-info input").each(function() {
          if ($(this).val() == "") {
            console.log('algo');
            $(this).addClass('required');
          }
        });
        return false;
      }
    } else if (currStep == 3) {
      if ($('input[name="wood_state"]').is(':checked')) {
        return true;
      } else {
        $('input[name="wood_state"]').addClass('required');
        return false;
      }
    } else if (currStep == 4) {
      if ($("input#city").val() != "" &&
        $("input#name").val() != "" &&
        $('input#email').val() != "" &&
        $('input#phone').val() != ""
      ) {
        return true;
      } else {
        $(".client-info input").each(function() {
          if ($(this).val() == "") {
            $(this).addClass('required');
          }
        });
        return false;
      }
    }
  }

  function sendForm() {
    let formData = $("form#quote").serializeArray();
    console.log(formData);
    $.ajax({
      type: 'POST',
      dataType: "html",
      url: postmain.ajaxurl,
      data: {
        form: formData,
        action: 'quote_form_handle',
      },
      beforeSend: function() {
        $('.nav-quote-form button.next-step').addClass('sending');
        $('.nav-quote-form .next-step span.txt').text('Espere por favor..');
        $('.loader-form').fadeIn(300);
      },
      success: function(response) {
        console.log(response);
        $('.loader-form').fadeOut(300);
        $('.nav-quote-form button.next-step').removeClass('sending').addClass('sent');
        $('.nav-quote-form .next-step span.txt').text('Presupuesto enviado');
        clearForm();
      },
      error: function(err) {
        console.log(err);
      }
    });
  }
  let currCat = `<?php $term = get_queried_object();
                    echo $term->slug;
                    ?>`;
  console.log("se asigno currCat");
  console.log($currCat);
  currCat = currCat.toLowerCase();

  if (currCat) {
    console.log("entro if currCat");
    generateSelect();
    getOptions(currCat);
  } else {
    generateSelect();
  }

  let optionsDynamic;

  function getOptions(woodFor) {
    console.log(woodFor);
    $.ajax({
      type: 'POST',
      dataType: "html",
      url: "<?php echo admin_url('admin-ajax.php'); ?>",
      data: {
        woodFor: woodFor,
        action: 'get_wood_type',
      },
      beforeSend: function() {

      },
      success: function(response) {
        console.log(response);
        optionsDynamic = response;
        $('#wood_type').empty();
        $('#wood_type').append(response);
        if (currCat) {
          $('.wood-for .next-step').click();
        }
        $('.select.wood_type ul').empty();
        generateOptions($('#wood_type'), $('.select.wood_type ul'));
      },
      error: function(err) {
        console.log(err);
      }
    });
  }

  function generateSelect() {

    // Iterate over each select element
    $('.quote-form select').each(function() {

      createSelect($(this));

      //cierre each
    });

  }

  function generateOptions($this, $list, numberOfOptions) {
    var numberOfOptions = $this.children('option').length;
    for (var i = 0; i < numberOfOptions; i++) {
      $('<li />', {
        text: $this.children('option').eq(i).text(),
        rel: $this.children('option').eq(i).val()
      }).appendTo($list);
    }
  }

  function createSelect(el) {
    // Cache the number of options

    var $this = el,
      numberOfOptions = el.children('option').length;

    // Hides the select element
    $this.addClass('s-hidden');

    // Wrap the select element in a div
    $this.wrap('<div class="select ' + el.attr('id') + ' "></div>');

    // Insert a styled div to sit over the top of the hidden select element
    $this.after('<div class="styledSelect"></div>');

    // Cache the styled div
    var $styledSelect = $this.next('div.styledSelect');

    // Show the first select option in the styled div
    $styledSelect.text($this.children('option').eq(0).text());

    // Insert an unordered list after the styled div and also cache the list
    var $list = $('<ul />', {
      'class': 'options'
    }).insertAfter($styledSelect);


    for (var i = 0; i < numberOfOptions; i++) {
      $('<li />', {
        text: $this.children('option').eq(i).text(),
        rel: $this.children('option').eq(i).val()
      }).appendTo($list);
    }

    // Cache the list items
    var $listItems = $list.children('li');
    console.log($listItems);

    // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)
    $styledSelect.click(function(e) {
      e.stopPropagation();
      $('div.styledSelect.active').each(function() {
        $(this).removeClass('active').next('ul.options').hide();
      });
      $(this).toggleClass('active').next('ul.options').toggle();
    });

    // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
    // Updates the select element to have the value of the equivalent option
    $listItems.click(function(e) {
      e.stopPropagation();
      $styledSelect.text($(this).text()).removeClass('active');
      $this.val($(this).attr('rel'));
      $list.hide();
      if ($styledSelect.hasClass('required')) {
        $styledSelect.removeClass('required');
      }
      console.log('clickee en la list', $this.val());
      if (!currCat) {
        console.log('clicked list', $this.val());
        getOptions($this.val());
      }

      /* alert($this.val()); Uncomment this for demonstration! */
    });

    // Hides the unordered list when clicking outside of it
    $(document).click(function() {
      $styledSelect.removeClass('active');
      $list.hide();
    });

    if (currCat) {
      console.log('currCat', $this.val());
      $("#wood_for option").each(function() {
        if ($(this).val() == currCat) { // EDITED THIS LINE
          $(this).attr("selected", "selected");
          $('.wood_for').find('div.styledSelect').text($(this).text())
        }
      });
    }

  }



  function clearForm() {
    $('.quote-form input').val('');
    $('.quote-form select').val('');
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...