根据URL查询字符串中的复选框值,在页面刷新后设置复选框

时间:2012-03-01 16:35:17

标签: javascript jquery regex url checkbox

我有一组复选框:

    <input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS&#160;&#160;
    <input name="LocType" type="checkbox"  value="Office"/>  PHYSICIAN OFFICES&#160;&#160;
    <input name="LocType" type="checkbox"  value="Emergency"/>EMERGENCY CENTERS&#160;&#160;
    <input name="LocType" type="checkbox"  value="Out-Patient"/>OUT-PATIENT CENTERS&#160;&#160;
    <input name="LocType" type="checkbox" value="Facility"/>FACILITIES

我已经按照以下方式抓取了它们的值并传递给了url,在使用传递的查询字符串重新加载页面之后,我想检查传递的任何复选框值并将这些复选框设置为checked = true。

var url = "http://mysite.com/contact-us/Pages/LocationSearch.aspx?s=bcs_locations&k=";     
var checkboxValues = $("input[name=LocType]:checked").map(function() {
    return ' '+'bcslocationtype:'+"\"" + $(this).val() + "\"";}).get().join(" OR ");                 

         window.location= url +  checkboxValues;

当选中Hospitals and Emergency复选框并点击搜索时,URL如下所示: http://mysite.com/contact-us/Pages/LocationSearch.aspx?s=bcs_locations&k= bcslocationtype:“医院”或bcslocationtype:“紧急”

现在为什么事情不起作用,我没有看到任何错误?它的insde document.ready(){}

//Keep the selected chkboxes checked on page redirect
    var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
    if (value.length == 2) {
        $('input[name=LocType]').each(function (index) {
            if(value[1].indexOf($(this).val())>=0)
                this.prop("checked", true); 
            }); 
    }  

1 个答案:

答案 0 :(得分:0)

以下是对代码的更新

 $(document).ready(function(){

   var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
   var actualValue = value[1].split(":")
    console.log(actualValue[1]);
    $('input[name=LocType]').each(function (index) {
            if(actualValue[1] === $(this).val()){
            //or use if(actualValue[1].indexOf($(this).val())>=0){
                $(this).prop("checked", true); 
            }

    }); 
});

另请注意,为了访问与'prop'相关的jquery相关方法,您需要在'$'中包含'this'。所以我将你的代码从'this'更新为'$(this)'。另外,我们的目的是使用'bcslocationtype:'Hospital“'作为价值。为什么需要'bcslocationtype'作为变量k的值。你不能只追加k =医院等吗?

另外,你可以使用aspx做同样的事情。我不确定aspx代码,但在Coldfusion中我会做类似下面的事情:假设'k'是url变量名

 <input name="LocType" type="checkbox" value="Hospital" <cfif isDefined("URL.k") and URL.k eq "HOSPITAL">CHECKED</cfif> />HOSPITALS&#160;&#160;

要读取的输入标记内的代码为<cfif isDefined("URL.k") and URL.k eq "HOSPITAL">CHECKED</cfif>。这意味着,如果我在URL范围内定义并设置了一个名为'k'的变量,并且该值是医院,则进行检查。将其转换为您的asp代码。