首页 > 解决方案 > 根据 URL 参数选中复选框

问题描述

我正在尝试根据 URL 中的参数检查表单上的各种复选框。

URL 可能类似于以下内容:

https://development.mycompany.com/project/home.php?profile=profile1,profle2&region=&rep=

如您所见,URL 中的“profile”参数有两个值(profile1、profile2)。

我有一个包含一系列复选框的表单,如下所示:

<input class="profileCheckbox" type="checkbox" id="PROFILE1CHECK" name="profileCheckbox" value="PROFILE1" />
<input class="profileCheckbox" type="checkbox" id="PROFILE2CHECK" name="profileCheckbox" value="PROFILE2" />
<input class="profileCheckbox" type="checkbox" id="PROFILE3CHECK" name="profileCheckbox" value="PROFILE3" />
// few more

使用 URL 参数,复选框 ID 的 PROFILE1CHECK 和 PROFILE2CHECK 应该被选中,而其他任何复选框都处于未选中状态。

我有这段代码可以抓取 URL 中的任何参数:

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = window.location.search.substring(1),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;
  
  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');
    
    if (sParameterName[0] === sParam) {
      return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
    }
  }
  return false;
};

var profile = getUrlParameter('profile');

console.log(profile);

当我控制台配置文件变量时,我可以看到以下内容:

profile1,profile2

这就是我卡住的地方。

我不太确定如何检查 PROFILE1CHECK 和 PROFILE2CHECK 的 ID 复选框。

标签: javascriptjqueryurlcheckboxdecodeuricomponent

解决方案


var profile = getUrlParameter('profile');
$("#PROFILE1CHECK").attr("checked",profile.indexOf("profile1") !== -1);

推荐阅读