Clarity Posted May 10, 2023 Share Posted May 10, 2023 Hello everyone! I need to create a form which appears to be a filter in which GET parameters will come with the same order as the user chooses it. Can you please tell me how to do it? Link to comment Share on other sites More sharing options...
flydev Posted May 10, 2023 Share Posted May 10, 2023 (edited) 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 May 10, 2023 by flydev changed example url 3 1 Link to comment Share on other sites More sharing options...
kongondo Posted May 10, 2023 Share Posted May 10, 2023 (edited) 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 May 10, 2023 by kongondo 2 1 Link to comment Share on other sites More sharing options...
Clarity Posted May 11, 2023 Author Share Posted May 11, 2023 Thank you very much! Link to comment Share on other sites More sharing options...
Recommended Posts