Solved

C#, ASP  How to check how many check boxes are checked

Posted on 2014-03-18
9
1,816 Views
Last Modified: 2014-04-11
Hello,
We have a web page with dynamically loaded check boxes (depends on how many records in database).
What i need is to make sure the user checks only 5 check boxes. And if he checks the 6th one, give him a message that he can only check 5.
ASP:
Please select up to five:
<asp:Repeater runat="server" ID="rptCandidats" >
        <ItemTemplate>
             <div>
                 <asp:checkbox id="chResponse" runat="server"  AutoPostBack="True"   OnCheckedChanged="Check_Clicked"></asp:checkbox>
<%# Eval("ResText")%> <a href="<%#Eval("ResLink")%>" class="moreinfo">   More Info</a>
                 <asp:HiddenField ID="ResId" runat="server" Value ='<%#Eval("ResponId")%>' />                           </div>
       </ItemTemplate>
</asp:Repeater>

Open in new window

I tried to use OnCheckedChanged event, but it doesn't work.
Below is a C# code:
protected void Check_Clicked(Object sender, EventArgs e)
       {
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
              CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += (sender as CheckBox).Checked ? 1 : -1;
               }
           }
           if (checkedCount > 5)
           {
               System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\"Only Up to five candidates can be selected.\")</SCRIPT>");
           }

       }

Open in new window

Any ideas how can i achieve it?
Thanks.
0
Comment
Question by:kqureshi321
  • 4
  • 3
9 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 39937648
Don't use response.Write.

use ScriptManager.RegisterStartupScript:
http://msdn.microsoft.com/en-us/library/bb359558%28v=vs.110%29.aspx


 string javaScript = "<script language=JavaScript>\n" + "alert('Only Up to five candidates can be selected');\n" + "</script>";

ScriptManager.RegisterStartupScript(updatePanelId,updatePanelId.GetType()
                                                      , "alert", javaScript, true);
0
 

Author Comment

by:kqureshi321
ID: 39937775
Thanks!
Here is my new code
 protected void Check_Clicked(Object sender, EventArgs e)
       {
           string sysAlert="Only up to five selections.";
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
               CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += (sender as CheckBox).Checked ? 1 : -1;
                   if (checkedCount > 5)
                   {
                      
       Page.ClientScript.RegisterStartupScript(this.GetType(), "This Alert", "alert('" + sysAlert + "');", true);
       cb.Checked = false;

                   }
               }
           }
          
       }

Open in new window

It is working, but now, when you click on the check box, the page blinking like it reloads .
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 39937803
take it out of the for each. and do you have your repeater ajaxified in an updatepanel?

protected void Check_Clicked(Object sender, EventArgs e)
       {
           string sysAlert="Only up to five selections.";
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
               CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += cb.Checked ? 1 : 0;
                }
           }
          
        if (checkedCount > 5)
        {

       Page.ClientScript.RegisterStartupScript(this.GetType(), "This Alert", "alert('" + sysAlert + "');", true);
       cb.Checked = false;
        }

       } 

Open in new window

0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:kqureshi321
ID: 39937993
I'm sorry, i'm new to it.
There is no updatepanel.
And why remove For each if i need to count how many check boxes are already checked?
Am i doing something wrong?
0
 
LVL 52

Accepted Solution

by:
Scott Fell,  EE MVE earned 250 total points
ID: 39938481
I'm not a .NET dev.   An alternative would be to do this in javascript and avoid the call to the server.  You would still want to test serverside for more than 5 checks.  This is one way to do what I think you want on the front end.

A live sample http://jsbin.com/visiy/1/edit where I used the jquery docs as the base.  http://api.jquery.com/checked-selector/
<!DOCTYPE html>
<html>
<head>
<style>
  .error{background-color:pink;padding:5px;}
  </style>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
    $(function() {
    var countChecked = function () {
    var n = $("input.chResponse:checked").length;
    if (n > 5) {
        $('#myButton').prop('disabled', true);
       
        $('div.msg').addClass('error').html('You have checked more than 5 boxes.  The submit button has been disabled.  Please check only 5 boxes');
    } else {
        $('#myButton').prop('disabled', false);
        $('div.msg').removeClass('error').html('Please check no more than 5 boxes');
    }
};
countChecked();

$("input[type=checkbox].chResponse").on("click", countChecked);
    });      
  </script>
</script>
  <meta charset="utf-8">
  <title>EE Q_28391393</title>
</head>
<body>
<input type="checkbox" class="chResponse">check1<br>
<input type="checkbox" class="chResponse">check2<br>
<input type="checkbox" class="chResponse">check3<br>
<input type="checkbox" class="chResponse">check4<br>
<input type="checkbox" class="chResponse">check5<br>
<input type="checkbox" class="chResponse">check6<br>
<input type="checkbox" class="chResponse">check7<br>
<input type="checkbox" class="chResponse">check8<br>
  <div class="msg">Please check no more than 5 boxes</div>
  <button id="myButton">Submit</button>
</body>
</html>

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 39939681
@kqureshi321

If you see the code I modified I still use the for each, I just moved the register script out of it.  

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_28391393.html#a39937803
0
 

Author Comment

by:kqureshi321
ID: 39939872
Even with this change, the page still blinks like it reloads.
0
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 250 total points
ID: 39940364
that's coming from the postback.


add this to your front end:

<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate >
  <! --- repeater goes in here -->
</ContentTemplate >
</UpdatePanel>

You can also take the javascript approach . . . but I've never been a fan of it for maintenance reasons.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question