【问题标题】:How to pre-populate checkboxes based on URL parameters如何根据 URL 参数预填充复选框
【发布时间】:2021-07-04 19:51:25
【问题描述】:

我正在尝试根据 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&amp;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>

【问题讨论】:

  • 1. if 比较应该有 ==。 2. 使用URLSearchParams。 3. valueid 应该在引号内
  • 固定第 1 点和第 3 点,但对于第 2 点,您的意思是像 URLSearchParams(window.location.search.substring(1))
  • 在 html 代码中 idvalue 将用双引号引起来。在javascript中这样做document.getElementById(window.location.href.split("?a=")[1]).checked=true
  • 嗯,它对单个参数有效,但对多个参数无效?a=1&amp;a=3 也许我应该更清楚一点。

标签: javascript html checkbox


【解决方案1】:

你可以遵循这种方法

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>

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2011-09-08
    • 1970-01-01
    • 2013-11-03
    相关资源
    最近更新 更多