I wonder if is possible to add DropDown item in the Page instead of Code-behind?
So say I have a DropDown box I want to show year 1900 ~ current year
<asp:DropDownList ID="ddlYear" runat="server" CssClass="text">
<%
int currentYear = DateTime.Now.Year;
for (int i = 1900; i < currentYear; i++)
{
%>
<asp:ListItem><%=i %></asp:ListItem>
<%
}
%>
</asp:DropDownList>
Is it possible to do something like that?
Because when I try to do like above it gives me:
Warning 1 C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx:
ASP.NET runtime error: Code blocks are not supported in this
context. C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx 35 1 MyWebApplication1
Edit: I also tried:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<%
int currentYear = DateTime.Now.Year;
if (currentYear <= 1933)
{
currentYear = 2012;
}
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
%>
But the DropDownList doesn't have items when display...
=====
Edit: As Splash-X suggested, now it rendered, but all items gone after postback....
<form id="form1" runat="server">
<div>
<%
int currentYear = DateTime.Now.Year;
if (!Page.IsPostBack)
{
if (currentYear <= 1933)
{
currentYear = 2012;
}
DropDownList1.Items.Clear();
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
}
%>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<input id="Button1" type="button" value="button" onclick="MyFunction();"/>
<div id="MyDiv">
</div>
<asp:Button ID="Button2" runat="server" Text="Button" />
</div>
</form>
I don't beleive it is. You can have script blocks in the page rather than in the code behind but they would be coded in the same way as the codebehind would be (ie method blocks and referring to the dropdown as an object and calling add methods, etc.) so you are not really gaining anything by doing it in the page.
I had an instance where we had a project written in ASP.NET 2.0 and we no longer had the source code to make changes. We needed to modify the states that were being displayed in a dropdown. The old code had US States and Canadian Provinces and we needed to display States only. The dropdown was bound to data source in the code behind so we clear the items and then add all of the items.
<%
if(!IsPostBack)
{
st.Items.Clear();
st.Items.Add(new ListItem("State", "")); //Add an empty item at the top for default value
string usStates = "AA,AE,AK,AL,AP,AR,AS,AZ,CA,CO,CT,DC,DE,FL,FM,GA,GU,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MH,MI,MN,MO,MP,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,PW,RI,SC,SD,TN,TX,UT,VA,VI,VT,WA,WI,WV,WY";
foreach (string state in usStates.Split(','))
{
st.Items.Add(new ListItem(state, state));
}
}
%>
<select name="st" class="col" id="st" alt="select" runat="server">
The difference is I'm doing my modifications BEFORE the control and the reason I had to do this is any script that comes after the control is changing the dropdown after it is rendered out to the page.
Try moving your code above the dropdown list. Our code checks to see if there was a post back so we could preserve any value that was previously entered. There is no point reloading the list on every page load, just the first.
Related
I'm trying to create a quiz in web application in asp.net C# using a database. The quiz has 25 question and 5 answers and each answer has a number of points(totally agree(1),agree(2), not sure(3), disagree(4), totally disagree(5)).
The questions and answers are in a database.
What I want is when i click on the submit button to calculate the score from those questions and put the score in a table from my database.
I try to do a if (radiobutton1.checked){
score=2}
but it doesn't work because of the repeater...I guess i'm not sure.
I try to delete the repeater but when i done that the questions and answers do not display on the web page.
In my aspx file i write code to display my data from database like that(using a repeater and table):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td> <%#Eval("IDq") %> ) <%#Eval("qustion") %></td></tr>
<tr>
<td>
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%#Eval("ans1")%>' GroupName="quiz" Value="1"></asp:RadioButton>
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%#Eval("ans2") %>' GroupName="quiz" Value="2"></asp:RadioButton>
<asp:RadioButton ID="RadioButton3" runat="server" Text='<%#Eval("an3") %>' GroupName="quiz" Value="3"></asp:RadioButton>
<asp:RadioButton ID="RadioButton4" runat="server" Text='<%#Eval("ans4") %>' GroupName="quiz" Value="4"></asp:RadioButton>
<asp:RadioButton ID="RadioButton5" runat="server" Text='<%#Eval("ans5") %>' GroupName="quiz" Value="5"></asp:RadioButton>
<br />
</td>
</tr> </table>
</ItemTemplate></asp:Repeater>
Ok, you have a good start.
And I am going to suggest that in place of the RadioGroup tag?
That DOES get you automatic ONLY one choice. The problem is we STILL will have to check all 5 controls.
A better control in this case to use what is called a RadioButtonList. It works VERY much like having used RadioGroup, but the REALLY nice part?
It is ONE control, and if there are 3 or 15 choices for Radio button group, it as ONE control returns
the index of the selection (0 to N)
the text value of the selection
the value value of the selection.
So I recommend using a RadioButton list - since it is "one thing" that returns the selections.
The "major" problem with the RadioButtonList is you CAN'T use those cool data bound expresisons ike you are using now (that was a good call/design on your part).
However, either we write a loop to "get/check" the 5 raido buttons, or we write a loop to fill the Radiobutton list - I think using code to fill out the RadioButton list is a better choice.
Also, you new - and I see you are attempting to use some "table and "tr" to help you lay out things. You don't really need this.
Now, because ALL of the above ideas saves us so much time, so much code? Well, then we can add extra code to say
show the score and results after we submit
tell the user they did NOT answer a question - they MUST!!!
heck, toss is a cool check box, or X box to show wrong or right.
Allow a question to only have say 2 answers - not always all 5
Ok first up, our table - it looks like this:
So, we have the IDq (id of question). The 1 to 5 possible answers, and then a column with the CORRECT answer.
Ok, now our markup. As I stated, since we reduced so much markup and code, then I added the message in big bold red that appears when a user did not answer all questions.
And I also added a "results" box that shows when you hit submit (number wrong, and correct).
So, now our Markup becomes like this:
<div style="width:35%">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="float:left">
<asp:Label ID="Question" runat="server"
Text = '<%# Eval("IDq").ToString + " ) " + Eval("question") %>'
Font-Size="X-Large">
</asp:Label>
</div>
<div style="float:right">
<img id="MyImage" runat="server" src="" height="48" width="48" />
</div>
<div style="clear:both">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" ></asp:RadioButtonList>
</div>
<br />
<hr></hr>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="cmdDone" runat="server" Text="Submit" />
<div id="MyError" style="display:none;normal;color:red" runat="server">
<h2>You have not answered all questions</h2>
<h2>Please answer all questions before submitting</h2>
</div>
<div id="Results" runat="server" style="clear:both; display:none" >
<h2>Results</h2>
<asp:TextBox ID="MyCorrect" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="InCorrect" runat="server"></asp:TextBox>
</div>
</div>
so, not a lot of markup - and we added quite a bit new features.
I also tossed in the idea to show a check box for correct, and wrong - you can remove that part - but it does help you learn a lot here.
So, now when I run the code, I see this:
So note the questions I have correct. As I stated - you may well want to remove that.
And note the message that I not yet answered all questions.
So, as noted, we have a LITTLE bit more code to load up the Repeater, but less to check things after.
So, our code now looks like this:
private DataTable MyTable = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadData();
ViewState["MyTable"] = MyTable;
}
else
MyTable = ViewState["MyTable"];
}
public void LoadData()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblQuestions ORDER BY IDq",
new SqlConnection(My.Settings.TEST4)))
{
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = MyTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRow MyRow = MyTable.Rows(e.Item.ItemIndex);
RadioButtonList rBtnList = e.Item.FindControl("RadioButtonList1");
for (var i = 1; i <= 5; i++)
{
var strR = "ans" + i;
if (IsDBNull(MyRow(strR)) == false)
{
ListItem nItem = new ListItem(MyRow(strR), i);
rBtnList.Items.Add(nItem);
}
}
}
}
protected void cmdDone_Click(object sender, EventArgs e)
{
// check all rows - make sure all have a answer
// show check box for correct answers
// total up correct answers (count)
// total up wrong answers (count)
MyError.Style("Display") = "none";
int Correct = 0;
int Wrong = 0;
int NotAnser = 0;
foreach (RepeaterItem ritem in Repeater1.Items)
{
RadioButtonList RadioBut = ritem.FindControl("RadioButtonList1");
if (RadioBut.SelectedIndex >= 0)
{
HtmlImage MyImage = ritem.FindControl("MyImage");
if (MyTable.Rows(ritem.ItemIndex).Item("Answer") == RadioBut.SelectedIndex + 1)
{
Correct += 1;
MyImage.Src = "/Content/ok.png";
}
else
{
Wrong += 1;
MyImage.Src = "/Content/reject.png";
}
}
else
{
NotAnser += 1;
}
}
// if missed questions then display warning.
if (NotAnser > 0)
MyError.Style("Display") = "normal";
else
{
MyCorrect.Text = "Correct answers = " + Correct;
InCorrect.Text = "Wrong answers = " + Wrong;
Results.Style("Display") = "normal";
}
}
So you can see in that submit button code, we are NOW with great ease to loop the repeater, get the user answer, check against the table data.
And note the other trick - I persist MyTable into ViewState. I did this since I did not want to have to re-load the table each time - it just means for ANY button click, control and code behind? I ALWAYS have the data table at my fingertips
Now, given the above does total up the answer, then you would have to add 2-5 more lines of code to write out the total, or the results - it not clear if you plan to have some other table where you have say some student ID, or user id, and you save the total results of the test (or the correct count, or wrong count).
so, the final result looks like this:
I've been stuck for the last two hours and need help. I've tried every single example I could find online and none of them work. I'm building a web page in ASP.NET and want to make a list of buttons. Doesn't seem too hard right? It's been causing me issues though.
This is my code:
<ul>
<form id="tagloop" runat="server">
<% foreach (string i in data)%>
<%Response.Write("<li><button runat=\"server\" type=\"submit\" onserverclick=\"ClickTag\">" + i + "</button></li>");%>
</form>
</ul>
If I remove the Response.Write() it only loops once but the one button it does generate actually works and calls the method on click. Also, the variable i doesn't apply.
<ul>
<form id="tagloop" runat="server">
<% foreach (string i in data)%>
<li><button runat="server" type="submit" onserverclick="ClickTag"> i </button></li>
</form>
</ul>
Is there anyway I can get it to loop, have the text of i in data, and also call the correct function on click? I haven't been able to find a balance of all three yet and any help will be appreciated.
If you want to create server side controls, you're better off using an asp:Repeater:
<asp:Repeater runat="server" ID="Repeater1" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<li>
<asp:Button runat="server" ID="RepeaterButton" Text="<%# Container.DataItem %>" OnClick="RepeaterButton_Click"/>
</li>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack) return;
var data = new List<string> { "Test1", "Test2", "Test3", "Test4" };
Repeater1.DataSource = data;
Repeater1.DataBind();
}
You have to write a bit more code, but you avoid adding to much logic into your markup and do not have to use Response.Write, which is prone to errors and typos.
You can even do this with strongly typed objects!
Let's assume you have a person class:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
And you have a method in your .cs file that returns a list of Persons:
IEnumerable<Person> Persons()
{
for (int i = 0; i < 10; i++)
{
yield return new Person { FirstName = $"Foo{i}", LastName = $"Bar{i}" };
}
}
You can then reference your object properties in your repeater control:
<asp:Repeater runat="server" ID="Repeater1" ItemType="WebFormsSandbox.Person">
<ItemTemplate>
<li>
<asp:Button runat="server" ID="RepeaterButton" Text="<%#: Item.FirstName %> <%#: Item.LastName %>" OnClick="RepeaterButton_Click"/>
</li>
</ItemTemplate>
</asp:Repeater>
Reference: https://msdn.microsoft.com/en-us/library/x8f2zez5(v=vs.100).aspx
Something like this?
<form id="tagloop" runat="server">
<%
List<int> data = new List<int>();
data.Add(1);
data.Add(2); %>
<% foreach (int i in data)%>
<%Response.Write("<li><button runat=\"server\"
type=\"submit\"onclick=\"ClickTag\">" + i + "</button></li>");%>
</form>
I am having difficulty adding a Button control to a specific spot in an .aspx page. I think I can create the button, but I don't know how to add it to the page.
Code is as follows:
<%
var cpus = productItems.FindAll(t => t.Type == "cpu");
foreach (var cpu in cpus)
{ %>
<div class="row product cpu">
<div class="col-md-3">
<img class="center-block" src="Content/images/processor.jpg" />
<span class="price"><%= cpu.Price %></span>
<span class="addtocart">
<% Button b = new Button();
b.ID = "Button" + cpu.ID;
b.CommandArgument = cpu.ID.ToString();
b.Text = "Add to Cart";
b.OnClientClick = "Addtocart_Click";
%>
</span>
<br />
</div>
</div>
<% } %>
I can also create the Button as part of the productItems collection, but still presents the problem of how to render the button on the page.
I'm sure there's a better way to do this, just not sure where to look.
Thanks in advance.
In WebForms, you can make use of listing controls that have a concept of a DataSource (Some listing of objects) and a template which renders how each of those objects appear. In general, you should use these whenever you have a list of items that you want to render on the site.
In this particular case, you will probably want to make use of the ListView control. This allows you to define a layout template and an item template.
Your aspx markup would look like the following:
<asp:ListView ID="lvCpus" OnItemDataBound="lvCpus_ItemDataBound" runat="server">
<LayoutTemplate>
<div class="row product cpu">
<div runat="server" id="itemPlaceholder"></div>
</div>
</LayoutTemplate>
<ItemTemplate>
<div runat="server" class="col-md-3">
<img class="center-block" src="Content/images/processor.jpg" />
<span class="price"><%# Eval("Price") %></span>
<span class="addtocart">
<asp:Button ID="addToCart" Text="Add To Cart" runat="server" />
</span>
</div>
</ItemTemplate>
</asp:ListView>
This defines a ListView control and creates a LayoutTemplate that matches your container. Internally it has a div that must have the id itemPlaceholder which is used to populate the various items that are bound to this control.
The ItemTemplate portion defines what you expect each individual item to look like. In this case, it's a column that contains a CPU for purchase.
Notice that the button is defined as a regular ASP Web Control, but none of the dynamic data is set. That's because if you try to assign a property like CommandArgument with an evaluated item, the server tag will not be well-formed and you'll get the YSOD. To work around this, you need to specify an OnItemDataBound function for the ListView that is called when you bind data to this Web Control. In my case, it's called lvCpus_ItemDataBound.
The ItemDataBound method in this case will look like the following:
protected void lvCpus_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var cpu = e.Item.DataItem as Cpu;
if (cpu == null)
{
return;
}
var btn = e.Item.FindControl("addToCart") as Button;
if (btn == null)
{
return;
}
btn.CommandArgument = cpu.Id.ToString();
// Set other server-side properties required from code.
}
}
When you bind a data source, it has 0 or more items in it. For every item in the data source, this method is called and will let you specify server-side appropriate values that can't be expressed directly in the template.
In our case, we specify the CommandArgument from the Cpu class, but other values could be specified as well.
Finally, we need to make sure we can fill the list view with data. So in Page_Load perhaps, we can bind data to this ListView like the following:
protected void Page_Load(object sender, EventArgs e)
{
lvCpus.DataSource = GetCpus();
lvCpus.DataBind();
}
private IEnumerable<Cpu> GetCpus()
{
yield return new Cpu { Id = 1, Price = 5 };
yield return new Cpu { Id = 2, Price = 10 };
yield return new Cpu { Id = 3, Price = 15 };
yield return new Cpu { Id = 4, Price = 15 };
yield return new Cpu { Id = 5, Price = 20 };
}
We first set the List View's data source to the CPU list that you have and then call the DataBind() method on the ListView. This triggers the OnItemDataBound function to begin filling in the data, and at the end you are left with, in this case, 5 CPUs displayed on the site.
I have added span as runatserver and add control(i.e. button) into it
Try below code,
<div class="row product cpu">
<div class="col-md-3">
<img class="center-block" src="Content/images/processor.jpg" />
<span class="price"><%= cpu.Price %></span>
<span class="addtocart" id="buttonContainer" runat="server">
<% Button b = new Button();
b.ID = "Button" + cpu.ID;
b.CommandArgument = cpu.ID.ToString();
b.Text = "Add to Cart";
b.OnClientClick = "Addtocart_Click";
buttonContainer.Controls.Add(b);
%>
</span>
<br />
</div>
</div>
In your situation, since you are using inline code, the below approach is the most optimal.
I have place a placeholder control to your original markup, that has an id of placeHolder1 at the location where the button needs to appear. This is what gives you total control over where the button will appear in the rendered page.
You need to use a placeholder control, which is a standard ASP.Net
control for adding controls dynamically at run-time.
You place the placeholder control at the location in your page markup where you would like the dynamically created button to appear.
Then, just use the line of code placeHolder1.Controls.Add(b); to add your button control.
Dynamically add a button at a certain location in your page
<%
var cpus = productItems.FindAll(t => t.Type == "cpu");
foreach (var cpu in cpus)
{ %>
<div class="row product cpu">
<div class="col-md-3">
<img class="center-block" src="Content/images/processor.jpg" />
<span class="price"><%= cpu.Price %></span>
<span class="addtocart">
<% Button b = new Button();
b.ID = "Button" + cpu.ID;
b.CommandArgument = cpu.ID.ToString();
b.Text = "Add to Cart";
b.OnClientClick = "Addtocart_Click";
placeHolder1.Controls.Add(b);
%>
<asp:PlaceHolder ID="placeHolder1" runat="server"></asp:PlaceHolder>
</span>
<br />
</div>
</div>
<% } %>
I have created a user control that is a textbox with some validation which I am adding dynamically to a grid. The grid's data source is from a dataset.
Because of this I am looping through my grid and loading the control to specific cells in the grid where I want them to be.
The problem I have is because I am adding this control dynamically, this somehow stops the validation from working.
User Control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TextboxPercentage.ascx.cs"
Inherits="tesco.User_Controls.TextboxPercentage" %>
<%# register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc2" %>
<div id="percentage">
<asp:TextBox runat="server" ID="txtPercentage" Width="40" onfocus="if (this.value=='0') this.value='';" onblur="if
(this.value=='') this.value='0';" Text="0"></asp:TextBox>
<asp:Label runat="server" ID="lbl1">%</asp:Label>
<asp:RegularExpressionValidator ID="Reg_percentage" ControlToValidate="txtPercentage"
runat="server" ErrorMessage="Numbers with 18 digits and two decimal values only. eg.9999999.99"
Display="None" ValidationExpression="\b\d{1,18}\.?\d{0,2}" Enabled="true"></asp:RegularExpressionValidator>
<asp:RangeValidator ID="rval_percentage" ControlToValidate="txtPercentage" MinimumValue="0"
MaximumValue="100" Type="Double" runat="server" ErrorMessage="Numbers between 0-100 only" Display="None" ></asp:RangeValidator>
<cc2:ValidatorCalloutExtender ID="vce_percentage_value" runat="server" TargetControlID="Reg_percentage"
Enabled="True">
</cc2:ValidatorCalloutExtender>
<cc2:ValidatorCalloutExtender ID="vce_percentage_range" runat="server" TargetControlID="rval_percentage"
Enabled="True">
</cc2:ValidatorCalloutExtender>
Code behind
GridView1.DataSource = ds;
GridView1.DataBind();
AssignCellCoordinates();
private void AssignCellCoordinates()
{
// Create IDs for Grid
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].ID = "r" + i; // Row ID
for (int ii = 0; ii < GridView1.Rows[i].Cells.Count; ii++)
{
GridView1.Rows[i].Cells[ii].ID = "c" + ii; // Cell ID
if (GridView1.Rows[i].ID == "r25" || GridView1.Rows[i].ID == "r26" || GridView1.Rows[i].ID == "r27")
{
if (GridView1.Rows[i].Cells[ii].ID != "c0")
{
User_Controls.TextboxPercentage txtPerc = (User_Controls.TextboxPercentage)LoadControl("~/User_Controls/TextboxPercentage.ascx");
GridView1.Rows[i].Cells[ii].Controls.Add(txtPerc);
}
}
}
}
}
As you can see I loop through a row and for each row iteration I add cell IDs until I reach total cells for one row. Within my inner loop I add the control if its certain cell id. But my validation doesn't work.
Anyone have ideas why this is?
Thanks
Dynamically created controls are lost on every postback. I would recommend adding the usercontol to your markup to prevent following scenarios:
People often run into problems with there usercontrols not showing.
Usercontrols events not getting fired, because the usercontrols do not exist in the markup instead are dynamically generated.
There is no difference in the speed(page-size). You can toggle there visibility according to your needs.
Much cleaner, elegant solution.
Anyways if you really need adding table dynamically, have a look at this question Dynamic Controls and Postback and this tutorial https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
Good Afternoon Developer,
this is my content in asp .net, I want the user can check only 2 checkbox,exceeding that alert box should pop up.
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td>
<asp:CheckBox id="q3a" runat="server" Text="Public" />
</td>
<td>
<asp:CheckBox id="q3b" runat="server" Text="void" />
</td>
<td>
<asp:CheckBox id="q3c" runat="server" Text="protected"/>
</td>
<td>
<asp:CheckBox id="q3d" runat="server" Text="return" />
</td>
</tr>
</table>
<asp:Button ID="btnSubmit" Text="submit" runat="server"/>
</div>
</form>
</body>
how can i write javascript for this, i have tried but can't find any way out, Pls help...
You should stop the user the instant they try and select a third option so that only two checked values can ever be submitted and avoid server side validation.
The client side onchange event should be hooked up to a function similar to this;
function validationCheck(checkbox) {
if(checkbox.checked) {
var count = 0;
count += document.getElementById('q3a').checked ? 1 : 0;
count += document.getElementById('q3b').checked ? 1 : 0;
count += document.getElementById('q3c').checked ? 1 : 0;
count += document.getElementById('q3d').checked ? 1 : 0;
if(count > 2) {
alert('You may only select two options.');
checkbox.checked = false;
}
}
}
The input should render with onchange="validationCheck(this);".
You could use JQuery:
$("input[type='checkbox']").change(function () {
var n = $("input:checkbox:checked").length;
if (n > 2) {
alert('2 are already selected!');
$(this).attr("checked", false);
}
});
If you really want to use JavaScript try this function:
function checkCondition(chkbox) {
var buttonGroup = document.getElementsByName("group");
var total = 0;
for (var i = 0; i < buttonGroup.length; i++) {
if (buttonGroup[i].checked) {
total++;
}
}
if (total > 2) {
alert('2 are already selected!');
chkbox.checked =false;
}
}
And also set onclick="checkCondition(this)" on your checkboxes and set their name attribute to the group value for example
agree with #Tim you can just write an on_click function for all checkboxes and then validate there if more then two chekboxes are selected and display error message when needed.
You could use jQuery to find all selected checkboxes:
var count = $("input:checked").length;
Then you have all you need.
But i would recommend to use the builtin ASP.NET-Validator Controls. You could use a CustomValidator for this purpose which would also work on clientside with an appropriate ClientValidationFunction.
You could add a client side onclick event for the check box and using jQuery you can check if the check box is checked. You can have a counter that should measure the threshold and then pop up the message if it exceeds.
$('.mycheckbox').click(function(){
var count = $("input:checked").length;
}
Note: Please add a classname property to all the checkboxes with same class name.