问题
I have a set of checkboxes:
<input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS  
<input name="LocType" type="checkbox" value="Office"/> PHYSICIAN OFFICES  
<input name="LocType" type="checkbox" value="Emergency"/>EMERGENCY CENTERS  
<input name="LocType" type="checkbox" value="Out-Patient"/>OUT-PATIENT CENTERS  
<input name="LocType" type="checkbox" value="Facility"/>FACILITIES
I have grabbed their values as follows and passed to the url, after page reloads with the passed querystring, i wanna check for whatever checkboxes values were passed and set those checkboxes to 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;
When Hospitals and Emergency checkboxes are checked and hit search, URL looks like this: http://mysite.com/contact-us/Pages/LocationSearch.aspx?s=bcs_locations&k= bcslocationtype:"Hospital" OR bcslocationtype:"Emergency"
Now why is thing not working, I don't see anything wrong with this?its 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:
Here is the update to your code
$(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);
}
});
});
Also note that, in order to access jquery related methods like 'prop', you need to wrap 'this' in '$'. So I updated your code from 'this' to '$(this)'. Also, what us the purpose of using 'bcslocationtype:"Hospital" ' as value. Why do you require 'bcslocationtype' as a value for variable k. Can't you just append k=hospital etc?
Also, you can do the same thing using aspx. I am not sure about the aspx code, but in Coldfusion I would do something like below: Assuming 'k' is the url variable name
<input name="LocType" type="checkbox" value="Hospital" <cfif isDefined("URL.k") and URL.k eq "HOSPITAL">CHECKED</cfif> />HOSPITALS  
The code within input tag to peruse is <cfif isDefined("URL.k") and URL.k eq "HOSPITAL">CHECKED</cfif>
. It means, if I have a variable called 'k' defined and set in URL scope, and if the value is hospital, make it checked. Convert it into your asp code.
来源:https://stackoverflow.com/questions/9520157/set-checkboxes-checked-after-page-refresh-based-on-checkboxes-values-in-the-url