dimanche 4 juillet 2021

How to pre-populate checkboxes based on URL parameters

I am trying to pre-populate checkboxes based on URL parameters. I have no experience with javascript so I can't get other solutions to work for me.

Consider the following setup:

<form method='GET'>
  <input type="checkbox" name="a" value="1" id="1"/>
  <input type="checkbox" name="a" value="2" id="2"/>
  <input type="checkbox" name="a" value="3" id="3"/>
  <button type="submit">Apply</button>
</form>

I want the second checkbox and first checkbox to be ticked when ?a=2&a=1 is observed in the URL.

This is what I have tried but the code does not work.

<script>
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');

for (i in sURLVariables) { 
  let sParameter =sURLVariables[i].split('='); 
  let name=sParameter[0];
  let value=decodeURIComponent(sParameter[1]);
  let id=decodeURIComponent(sParameter[1]);

  let collection = document.getElementById(id)
  for(j in collection){
    if(collection[j].id==id)collection[j].checked=true
  }
}
</script>



Aucun commentaire:

Enregistrer un commentaire