0

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>
5
  • 1. if comparison should have ==. 2. Use URLSearchParams. 3. value and id should be inside quotes Commented Jul 4, 2021 at 11:19
  • Fixed points 1 & 3 but for point 2 do you mean something like URLSearchParams(window.location.search.substring(1)) Commented Jul 4, 2021 at 11:27
  • 1
    developer.mozilla.org/en-US/docs/Web/API/URLSearchParams. You don't have to manually split and check Commented Jul 4, 2021 at 11:28
  • 1
    in html code id and value will be in double quotes. and in javascript this do this document.getElementById(window.location.href.split("?a=")[1]).checked=true Commented Jul 4, 2021 at 11:31
  • Mmm, it works for single parameter but fails for multiple ?a=1&a=3 Maybe I should have made that clearer. Commented Jul 4, 2021 at 11:42

1 Answer 1

1

You can follow this kind of approach

let fakeQueryString = "a=2&a=3"; //replace it with actual url
let searchParms = new URLSearchParams(fakeQueryString);

for(const [key,val] of searchParms)
  document.getElementById(val).checked = true;
<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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.