如何根据 URL 参数预填充复选框
How to pre-populate checkboxes based on URL parameters
我正在尝试根据 URL 参数预填充复选框。我没有使用 javascript 的经验,所以我找不到适合我的其他解决方案。
考虑以下设置:
<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>
我希望在 URL 中观察到 ?a=2&a=1
时勾选第二个复选框和第一个复选框。
这是我试过的方法,但代码不起作用。
<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>
你可以按照这种做法
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>
我正在尝试根据 URL 参数预填充复选框。我没有使用 javascript 的经验,所以我找不到适合我的其他解决方案。
考虑以下设置:
<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>
我希望在 URL 中观察到 ?a=2&a=1
时勾选第二个复选框和第一个复选框。
这是我试过的方法,但代码不起作用。
<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>
你可以按照这种做法
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>