2012-03-01 57 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代碼。