2012-03-01 55 views
0

我有一组复选框复选框值页面刷新后检查:组复选框基于URL查询字符串

<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,可通过重新加载页面后querystring,我想检查任何复选框值传递和设置复选框检查=真。

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; 

当医院和紧急复选框被选中,并点击搜索,网址如下: 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); 
      }); 
    } 

回答

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); 
      } 

    }); 
}); 

还要注意的是,为了获得jquery相关的方法,如“道具”,你需要用“这”在“$”。所以我将你的代码从'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代码。