I am making a checklist form and currently i am able to append the value of the selected boxes to the url in I feel an inefficient way and the main issue is that the state of the checkbox doesnt save either so a user cant see what they checked or uncheck.
This is the html code
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()">
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()">
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()">
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()">
</form>
This is the script to make the url
let form = document.getElementById("carForm")
let checkboxes = document.getElementsByTagName("input")
var vals = "";
let formSubmit = () => {
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals = checkboxes[i].value
// append checkbox values to url
var url = window.location.href;
if (url.indexOf('?') > -1){
// if a paramter already exists, append using
url += `&make=${vals}`
}else{
url += `?make=${vals}`
}
window.location.href = url;
}
console.log(vals);
}
}
function checkboxChanged() {
formSubmit()
}
</script>
So for instance if kia and honda were selected the url would be
/inventory?make=kia&make=honda
So if this is inefficient whats a better way of doing this and how do i ensure the checkbox state is persisted after the page is reloaded I am using nodejs/expressjs on server side and ejs