I'm working on some legacy inline Web Forms code. I have added a checkbox which is set by default. The issue is when the checkbox is unchecked, it still flips to checked when the form is submitted. There are no page event handlers per say.
In the JavaScript, if I set an alert it displays the value as blank which is correct when the checkbox is unchecked. However, the checkbox always reverts to its checked state when the form is submitted.
Markup:
<input type="hidden" id="inYard" name="inYard" runat="server" />
<input type='checkbox' id="excludeYard" name='excludeYard' onclick="CheckYardSelection()"
runat="server" />Include Items in Yard
JavaScript:
function CheckYardSelection()
{
var yardCheckbox = document.getElementById('excludeYard');
if (!yardCheckbox.checked)
document.getElementById('inYard').value = "";
else
document.getElementById('inYard').value = "Y";
}
C#:
<script runat="server">
...
if(!String.IsNullOrEmpty(Request.Form["inYard"]))
{
if (Request.Form["inYard"].ToString() == "Y")
{
excludeYard.Value = Request.Form["inYard"].ToString();
excludeYard.Checked = true;
}
}
...
</script>
You don't post your complete code but if you implement everything this way, you shouldn't get this issue anymore:
aspx file:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms._Default" %>
<script src="Default.js" language="javascript" type="text/javascript"></script>
<form runat="server">
<input type="hidden" id="inYard" name="inYard" runat="server" />
<input type='checkbox' id="excludeYard" name='excludeYard' onclick="CheckYardSelection()" runat="server" />
<input type="submit" value="Post" />
</form>
Code behined:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Request.Form["inYard"]))
{
if (Request.Form["inYard"].ToString() == "Y")
{
excludeYard.Value = Request.Form["inYard"].ToString();
excludeYard.Checked = true;
// query += " AND IC.NewWellPad <> 'YARD'";
}
}
}
}
Default.js
function CheckYardSelection() {
var yardCheckbox = document.getElementById('excludeYard');
if (!yardCheckbox.checked)
document.getElementById('inYard').value = "";
else
document.getElementById('inYard').value = "Y";
}