mercredi 22 février 2023

How to format html form checkbox URL parameters to \?var1=X,Y,Z&var2=A,B,C&var3=1,2,3

I have developed a job board and need to give the user 3 types of filters:

  • Job Type

    • 1
    • 2
    • 3...
  • Region Name

    • 1
    • 2
    • 3...
  • Salary Range

    • 1
    • 2
    • 3...

I want to send the results of a user checking any combination of boxes to the URL and have it formatted like /?JT=1,3&RN=2,3&SR=1

With the help of @darkbee I have this code which works for one variable, but I didn't have the foresight to ask how to do it for three:

document.addEventListener("DOMContentLoaded", function() {
  let form = document.getElementById('myform');
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    let checkboxes = [];
    document.getElementsByName('JT').forEach(function(checkbox) {
      if (checkbox.checked) checkboxes.push(checkbox.value);
    });
    window.location = '?JT=' + checkboxes.join(',');
  });
});
<form id="myform">
  <div class="form-group">
    <input type="checkbox" name="JT" value="1">
    <label>Label X</label>
    <input type="checkbox" name="JT" value="2">
    <label>Label Y</label>
    <input type="checkbox" name="JT" value="3">
    <label>Label Z</label>
  </div>
  <div class="form-group">
    <button type="submit" class="button button1">Submit</button>
  </div>
</form>

I tried to solve the problem with three separate forms, each with DarkBee's modified code, but I could get to work was one at a time - that is, I couldn't choose checkboxes from multiple filter options.

If anyone can help, I'd be very happy.




Aucun commentaire:

Enregistrer un commentaire