Reputation: 47
Here is my problem :
I want to manage the state of a checkbox in a webform page using visual studio 2010 to which i have reduced the code to the strict minimum for you to better understand my problem.
In order to get the state of my checkbox dynamically created i have tried severals things :
getElementById
but when i check with the debugger, the variable is always null
In fact i think i just need to act when the page is fully loaded but i don't know how.
I just need to know if my checkbox is on or off.
Here is the body content :
<body>
<form id="form1" runat="server">
<div class="checkbox1" id="CB1">
<input type="checkbox" value="1"/>
</div>
</form>
<script type="text/javascript">
$(function () {
$('input[type=checkbox]').switchButton({
button_width: 10,
labels_placement: "left",
height: 22,
width: 50
});
})
</script>
</body>
The jquery script is there : Jquery
The css for the particular checkbox is there : Css
Let me know how to make this work.
Upvotes: 3
Views: 251
Reputation: 1748
switchButton
(which I've developed) doesn't delete or modify the initial checkbox input you apply the plugin to...
So I suggest you create your checkbox just like you would in any other project and get its state through C# code...
I guess that's what other people have suggested here already.
Upvotes: 1
Reputation: 2363
You could create the checkbox as asp:checkbox then on client side using clientID call switchButton
function on it.
If you don't know how many checkboxes you will need, then you can create the checkboxes with name attribute and on server side access it like this Request["checkBoxName"]
.
You can do something like this to create many checkboxes and get their values easily:
Dictionary<string, bool> data = new Dictionary<string, bool>();
foreach (var item in Request.Params)
{
//code_chkId_001, true
if (item != null && item.ToString().StartsWith("code_"))
{
data.Add(item.ToString().Replace("code_", "")/*chkId_001*/ ,
Convert.ToBoolean(Request[item.ToString()]) /*true*/);
//you have to check here, if it's "on" instead of "true" ToBoolean will break.
}
}
I know this is like a hack, but I hate Asp.Net's postback and mainly use AJAX. Hope it helps.
Upvotes: 0
Reputation: 2126
Possible you need to do an Async Postback to your code behind Updating the Control Tree of your Page with the newly added Element. Otherwise C# has no way of knowing you add an element with jQuery.
The code should look like that
TextBox TitleTxtBox = new TextBox();
TitleTxtBox.ID = "TitleTxtBox";
this.Controls.Add(TitleTxtBox);
There is an article here that will help:
Another possible solution might be to request Request.Form to get the newly added element but i'm not sure if it works. Can't check it right now.
if (Request.Form["checkboxName"] != null && Request.Form["checkboxName"] == "on")
{
Response.Write("This checkbox is selected");
}
else
{
Response.Write("This checkbox is not selected");
}
http://forums.asp.net/t/1440174.aspx
Hope the above will help you.
Upvotes: 1