Jump to content

How to create a filter with GET parameters preserving order of user choice?


Clarity
 Share

Recommended Posts

Hi, 

With javascript you can achieve it easily. The idea is to add an event listener to each input and re-order an array when the user change an input:

<form id="form">
  <label for="filter1">filter 1 :</label>
  <input type="text" id="filter1" name="filter1"><br>

  <label for="filter2">filter 2 :</label>
  <input type="text" id="filter2" name="filter2"><br>

  <label for="filter3">filter 3 :</label>
  <input type="text" id="filter3" name="filter3"><br>

  <button type="submit" name="submit">Send ☑️</button>
</form>
<script>
  // get form and all input
  const form = document.querySelector('#form');
  const filter1_field = document.querySelector('#filter1');
  const filter2_field = document.querySelector('#filter2');
  const filter3_field = document.querySelector('#filter3');

  // array to store the order of the input
  const order = [];

  // listen for input fields change to update the order array
  filter1_field.addEventListener('input', () => updateOrderArray('filter1'));
  filter2_field.addEventListener('input', () => updateOrderArray('filter2'));
  filter3_field.addEventListener('input', () => updateOrderArray('filter3'));

  // update the order array
  function updateOrderArray(fieldName) {
    if (!order.includes(fieldName)) {
      order.push(fieldName);
    }
  }

  form.addEventListener('submit', (event) => {
    event.preventDefault(); 

    const baseUrl = 'https://example.test/form.php'; // L'URL de base
    // build the url with the GET parameters in the order specified by the order array
    let url = baseUrl;
    order.forEach((fieldName, index) => {
      const value = encodeURIComponent(document.querySelector(`#${fieldName}`).value);
      url += `${index === 0 ? '?' : '&'}${fieldName}=${value}`;
    });

    // redirect
    window.location.href = url;
  });
</script>

 

Result: /form.php?filter3=processwire&filter2=is&filter1=awesome

 

 

Edited by flydev
changed example url
  • Like 3
  • Thanks 1
Link to comment
Share on other sites

What @flydev said.

A slightly different alternative to the above is to store the order values in a hidden input as a CSV. In that case, you don't need to touch window.location.href. You would use the values in the CSV to access the GET params sequentially.

Edited by kongondo
  • Like 2
  • Thanks 1
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...