I have a website written in ASP.NET MVC and I have a parameter set to the page in question that specifies what the preceding page is. The reasoning for this is so when a user clicks an image from a particular page, the loaded page will automatically check the appropriate check box using javascript (jQuery particularly).
Here is the code that gets and sets the parameter:
<script type="text/C#" runat="server">
protected string Referrer = string.Empty;
protected override void OnLoad(EventArgs e)
{
try
{
Referrer = Request.UrlReferrer.Segments[2].ToLower();
}
catch (System.Exception)
{
Referrer = string.Empty;
}
base.OnLoad(e);
}
</script>
Next, here is the collection of check-boxes:
<div id="interestSelect1" class="interestPad">
<%= Html.CheckBoxFor(model => model.Interests[0])%>
<label for="Interests_0_">Insulation</label>
<%= Html.CheckBoxFor(model => model.Interests[1])%>
<label for="Interests_1_">Windows</label>
<%= Html.CheckBoxFor(model => model.Interests[2])%>
<label for="Interests_2_">Siding</label>
<%= Html.CheckBoxFor(model => model.Interests[3])%>
<label for="Interests_3_">Roofing</label>
</div>
<div class="clear">
</div>
<div id="interestSelect2" class="interestPad">
<%= Html.CheckBoxFor(model => model.Interests[4])%>
<label for="Interests_4_">Gutters/Protection</label>
<%= Html.CheckBoxFor(model => model.Interests[5])%>
<label for="Interests_5_">Patio Doors</label>
</div>
When rendered in the browser, here is what each of the check-boxes look like:
<input id="Interests_0_" name="Interests[0]" type="checkbox" value="true" />
<input name="Interests[0]" type="hidden" value="false" />
<label for="Interests_0_">Insulation</label>
Here is the javascript that I am using, that is not working:
<script type="text/javascript">
var ref = '<%= Referrer %>';
$(document).ready(function () {
switch (ref) {
case "insulation":
$('Interests_0_').attr('checked', 'checked');
break;
case "windows":
$('Interests_1_').attr('checked', 'checked');
break;
case "siding":
$('Interests_2_').attr('checked', 'checked');
break;
case "roofing":
$('Interests_3_').attr('checked', 'checked');
break;
case "gutters":
$('Interests_4_').attr('checked', 'checked');
break;
case "patiodoors":
$('Interests_5_').attr('checked', 'checked');
break;
default:
// do nothing, not valid ref
}
});
</script>
I am obviously doing something completely wrong, can anyone point me in the right direction?
Thanks!
EDIT: Looks like another JS file that was on a MasterPage that was called before my JS block was causing the boxes to not be checked. The main problem was forgetting the # identifier.
#idselectors need a#prefix, like this:Without the
#, it’s an element selector, looking for a<Interests_0_>element.You can slim it down overall with an object though, like this: