Url Button in Apply Filter will Change by Parameter Filter Choice

andysaktia

andysaktia

Posted on September 30, 2021

Url Button in Apply Filter will Change by Parameter Filter Choice

When I create a filter, and have multiple categories, I decide to fetch some and the rest in the bootstrap modal. The problem is that I want the modal filter to work like in archive.org where the user selects first and then applies the filter to the page.

Alt Text

Purpose

Change Applay Filter url for summit with various categories choice.

Prerequire

  • Javascripts; function, for
  • jQuery; selection and onclick features

Script

Pada buttom apply filter menggunakan id berpola applyName dan juga menyertakan nilai url terkait <buttom id="applyTag" url="http://www...>" yang kemudian akan di handle script berikut.

//<1>
$('#applyTag').on('click', function () {
   goUrlFilter('tag', this);
});
Enter fullscreen mode Exit fullscreen mode

Dimana fungsi goUrlFilter akan mengubah parameter url yang dimiliki buttom sesuai dengan kategori yang di check, tentunya dalam fungsi akan mengambil setiap kategori yang memiliki parameter name=tag di tag inputnya.

//<2>
function goUrlFilter(paramName, address){
  var markedCheckbox = document.getElementsByName(paramName);
  var url = $(address).attr('url');

  for (var checkbox of markedCheckbox) {
    if (checkbox.checked){
      url = url + '[' +  checkbox.value + ']';
    }
  }
   window.location.href = url;
};
Enter fullscreen mode Exit fullscreen mode

Untuk kasus filter yang banyak, untuk menjalankan fungsi, saya perlu sedikit trik, dengan menambahkan class btnApply pada setiap buttom applay, kemudian baru melakukan query untuk menjalankan script <1>.

//<3>
let btnApply = $('.btnApply');

btnApply.each(function(){
      let idApply = $(this).attr('id');
      let nameApply = idApply.split('apply')[1].toLowerCase();
      $(`#${idApply}`).on('click', function () {
         goUrlFilter(nameApply, this);
      });
});

Enter fullscreen mode Exit fullscreen mode

Done

💖 💪 🙅 🚩
andysaktia
andysaktia

Posted on September 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related