复选框过滤器数组值未加入url

时间:2018-10-26 11:56:56

标签: javascript jquery html

我正在尝试使用复选框创建一组过滤器。选中一个复选框后,该值将添加到url中,并相应地过滤页面内容。

就目前而言,过滤器和脚本正在运行,但是不是在URL中添加多个值并显示内容,而是覆盖了URL,并且仅使用复选框数组中的一个值。例如,如果选择了WordPress和XL,则仅WordPress将显示在URL中。我有一个该脚本的版本可以运行,但是对于选择选项没有问题,但是复选框证明存在问题,我不确定我错过了什么。

有人能指出我正确的方向吗? :)

Shopify.queryParams = {};
if (location.search.length) {
  for (var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
    aKeyValue = aCouples[i].split('=');
    if (aKeyValue.length > 1) {
      Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
    }
  }
}

jQuery('.coll-picker').change(function() {
  if (jQuery(this).val()) {
    location.href = '/collections/' + jQuery(this).val();
  }
  else {
    location.href = '/collections/all';
  }
});

/* Specify the input */
var collFilters = jQuery('.coll-filter');

collFilters.change(function() {
  delete Shopify.queryParams.page;

  /* declare an array */
  var newTags = [];
  // console.log(newTags);

  /* This works - if (this) is checked, push value from array : only working for one value though */
  collFilters.each(function() {
      //if (jQuery(this).val()) { // this works for select options
      if (jQuery(this).is(':checked')) {
      newTags.push(jQuery(this).val());
      // var id = $(this).attr("id"); alert("Checked: " + id);
    }
  });

  {% if collection.handle %}
  var newURL = '/collections/{{ collection.handle }}';
  if (newTags.length) {
    newURL += '/' + newTags.join('+');
  }
  var search = jQuery.param(Shopify.queryParams);
  if (search.length) {
    newURL += '?' + search;
  }
  location.href = newURL;
  {% else %}
  if (newTags.length) {
    Shopify.queryParams.constraint = newTags.join('+');
  }
  else {
    delete Shopify.queryParams.constraint;
  }
  location.search = jQuery.param(Shopify.queryParams);
  {% endif %}
});
<form class="lmwd-filter" method="post">
  <ul class="clearfix filter-category">
    <li>
      <p>Category</p>
      {% assign tags = 'Ecommerce, Woocommerce, WordPress, Magento 2' | split: ',' %}
      {% for t in tags %}
      {% assign tag = t | strip %}
      <label for="{{ tag }}">
        <input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
        {{ tag }}
      </label>
      {% endfor %}
    </li>
    <li><br /></li>
    <li>
      <p>Size</p>
      {% assign tags = 'XS, S, M, L, XL' | split: ',' %}
      {% for t in tags %}
      {% assign tag = t | strip %}
      <label for="{{ tag }}">
        <input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
        {{ tag }}
      </label>
      {% endfor %}
    </li>
  </ul>
</form>

0 个答案:

没有答案