show list selected no of list box on each checked - c#

I have a asp:CheckBoxList which load items from database.
I want to write a script which shows no. of checked checkbox on each check.
My aspx page is as following :
<div id="rfd-demo-zone2" class="placeholderContent accordionEmpGroup-child-subGroup-container">
<asp:CheckBoxList ID="ckbList2DesignationUc" runat="Server" RepeatLayout="Flow" RepeatDirection="Horizontal" Width="100%" ></asp:CheckBoxList>
</div>
script :
<script type="text/javascript">
$('#ckbList2DesignationUc input:checked').each(function () {
alert('hi');
});
</script>
In the above script I am trying to get an alert, but it is not showing

Put script in document.ready to ensure the availability of html elements to script and use attribute contains selector to find the checkboxes of the checkboxlist.
<script type="text/javascript">
$(document).ready(function(){
$('[id*=ckbList2DesignationUc]:checked').each(function () {
alert('hi');
});
});
</script>
To fire event on change of checkbox
<script type="text/javascript">
$(document).ready(function(){
$('[id*=ckbList2DesignationUc]').change(function () {
alert(this.id);
});
});
</script>

Client side:
$('.CheckBoxList').each(function () {
var items = new Array();
$(this).find("input:checkbox").each(function () {
if ($(this).attr("checked") == true) {
items[items.length] = $(this).next().html();
}
});
$(this).parent().find('.txtList').val(items.toString());
});
Html MarkUp:
<asp:TextBox runat="server" ID="txtabc" CssClass="txtList txtformatcss" Width="160px" ViewStateMode="Disabled"></asp:TextBox>
<asp:CheckBoxList ID="chkabc" runat="server"
RepeatLayout="Flow" CssClass="CheckBoxList">
</asp:CheckBoxList>
Here CheckBoxList is class name which have given in checkboxlist control

Possible solution:
<div id="rfd-demo-zone2" class="placeholderContent accordionEmpGroup-child-subGroup-container">
<asp:CheckBoxList ID="ckbList2DesignationUc" runat="Server" RepeatLayout="Flow" RepeatDirection="Horizontal" Width="100%" >
</asp:CheckBoxList>
</div>
and access it:
$("#<%=ckbList2DesignationUc.ClientID %> input[type=checkbox]:checked").each(function() {
alert('checked');
});

Try below code :
Solution-1
Whenever you will check checkbox an alert will show you the values of checked items in checkboxes.
Javascript code :
< script type="text/javascript">
function itemClick(radioButton) {
var Control;
var selectedItems;
selectedItems = '';
Control = document.getElementById("<%=ckbList2DesignationUc.ClientID %>").getElementsByTagName("input");
for (var i = 0; i < Control.length; i++) {
if (Control[i].checked == true)
selectedItems += i.toString()+',';
}
alert(selectedItems);
}
</script>
ASPX Code :
protected void Page_Load(object sender, EventArgs e)
{
for (int index = 0; index < 10; index++)
{
ckbList2DesignationUc.Items.Add(new ListItem("Item" + index, index.ToString()));
}
foreach (ListItem Li in ckbList2DesignationUc.Items)
{
Li.Attributes.Add("onclick", "return itemClick()");
}
}
Required solution by using Jquery :
Solution -2
< script type="text/javascript">
$(document).ready(function () {
var selectedCheckBoxes = '';
$('#ckbList2DesignationUc').each(function () {
var items = new Array();
$(this).find("input:checkbox").each(function () {
$(this).click(function () {
selectedCheckBoxes += $(this).val() + ",";
alert(selectedCheckBoxes);
});
});
});
});
< /script>
< asp:CheckBoxList ID="ckbList2DesignationUc" runat="Server" RepeatLayout="Flow" RepeatDirection="Horizontal" Width="100%">
< /asp:CheckBoxList>

This may help you: you can use it in code behind file as well as inside the script tag enable AutoPostBack property of checkboxlist to true
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
int i=0;
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected)
i++;
}
Response.Write(i);
}

Related

Unable to change visibility of a div in asp.net C#

I have a div that displays loading symbol. I am setting visibility on change of a dropdown box. I want to set its visibility to false in C# after the SelectedIndexChanged method is complete.
Here is the div tag :
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage" >
<img class="loadingImg" src="../Images/ajax-loader.gif" />
</div>
Here is the jQuery function :
$(document).ready(function () {
//$('#loadingImage').hide();
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "block";
});
});
and this is how i am trying to set the visibility in C#
protected void selectSegment_SelectedIndexChanged(object sender, EventArgs e)
{
ckBLBusinessUnits.Visible = true;
loadingImage.Style["display"] = "none";
}
I tried various ways in C# like set visibility to false etc but nothing worked. Kindly help.
Change this:
loadingImage.Style["display"] = "none";
To this:
loadingImage.Style.Add("display", "none");
You can use hide and show methods to perform that action.
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage">
<img class="loadingImg" src="loading.gif" />
</div>
<asp:DropDownList ID="selectSegment" ClientIDMode="Static"
runat="server">
<asp:ListItem Value="0">none</asp:ListItem>
<asp:ListItem Value="1">display</asp:ListItem>
</asp:DropDownList>
JS
$(document).ready(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
if (this.value === "1") {
$("#loadingImage").show();
} else {
$("#loadingImage").hide();
}
});
});
The div tag was outside of the updatepanel, moving the div inside of the updatepanel resolved the issue.

"CheckAll" checkbox works only with the first page of asp:Repeater. How to fix?

I have a Repeater with CheckBoxes:
<asp:Repeater ID="rpt_users" runat="server" OnItemCommand="rpt_users_ItemCommand" OnItemDataBound="rpt_users_ItemDataBound">
<HeaderTemplate>
<table id="usersTable">
<tr>
<th rowspan="2">All<br /><asp:CheckBox runat="server" ID="checkAll" OnCheckedChanged="checkAll_CheckedChanged"/></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="c0">
<td><asp:CheckBox ID="CheckSelect" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:Repeater>
Here's a script that I placed right after Repeater control:
<script type="text/javascript">
var repeater1Control = document.getElementById('<%= rpt_users.ClientID %>');
$('input:checkbox[id$=checkAll]', repeater1Control).click(function (e) {
if (this.checked) {
$('input:checkbox[id$=CheckSelect]', repeater1Control).attr('checked', true);
}
else {
$('input:checkbox[id$=CheckSelect]', repeater1Control).removeAttr('checked');
}
});
$('input:checkbox[id$=CheckSelect]', repeater1Control).click(function (e) {
//To uncheck the header checkbox when there are no selected checkboxes in itemtemplate
if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == 0) {
$('input:checkbox[id$=checkAll]', repeater1Control).removeAttr('checked');
}
//To check the header checkbox when there are all selected checkboxes in itemtemplate
else if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == $('input:checkbox[id$=CheckSelect]', repeater1Control).length) {
$('input:checkbox[id$=checkAll]', repeater1Control).attr('checked', true);
}
});
Unfortunately, It works only at the first page of repeater. If I go to the second page or further, then nothing happens when I press "CheckAll" checkbox in header. How to fix this issue?
try this
(function($){
var bindEvents = function(){
// bind events here;
var repeater1Control = document.getElementById('<%= rpt_users.ClientID %>');
$('input:checkbox[id$=checkAll]', repeater1Control).click(function (e) {
if (this.checked) {
$('input:checkbox[id$=CheckSelect]', repeater1Control).attr('checked', true);
}
else {
$('input:checkbox[id$=CheckSelect]', repeater1Control).removeAttr('checked');
}
});
$('input:checkbox[id$=CheckSelect]', repeater1Control).click(function (e) {
//To uncheck the header checkbox when there are no selected checkboxes in itemtemplate
if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == 0) {
$('input:checkbox[id$=checkAll]', repeater1Control).removeAttr('checked');
}
//To check the header checkbox when there are all selected checkboxes in itemtemplate
else if ($('input:checkbox[id$=CheckSelect]:checked', repeater1Control).length == $('input:checkbox[id$=CheckSelect]', repeater1Control).length) {
$('input:checkbox[id$=checkAll]', repeater1Control).attr('checked', true);
}
});
};
// initial load
$(document).ready( bindEvents);
// every async load by update panel
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(bindEvents);
})(jQuery);

Load second dropdown based on first - JQuery Dialog

I need to update my second drop down list from database according to the value selected from first drop down list in the Jquery dialog.
ASPX
<asp:UpdatePanel ID="upnl" OnLoad="upnl_Load" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="dv" style="display: none;" title="Tile">
<table>
<tr>
<td>Parent</td>
<td>
<asp:DropDownList ID="ddlDialog1" runat="server" /></td>
</tr>
<tr>
<td>Child</td>
<td>
<asp:DropDownList ID="ddlDialog2" runat="server" /></td>
</tr>
</table>
</div >
</ContentTemplate>
</asp:UpdatePanel>
JQuery
function EditBookingDialog() {
jQuery(document).ready(function () {
$("#dvEditBooking").dialog({
draggable: true,
modal: true,
width: 500,
height: 400
,
open: function (type, data) {
$("#<%= ddlDialog1.ClientID %>").change(function () {
__doPostBack('<%= upnl.ClientID %>', "DialogOnChange");
});
}
});
});
}
Code behind
protected void upnl_Load(object sender, EventArgs e)
{
if (arg.ToString().IndexOf("DialogOnChange") > -1)
{
// Here ddlDialog1.SelectedValue is always " ", Even I get a data set of values,ddlDialog2 is not populated with new values
ddlDialog2.DataSource = objMngr.GetData(ddlDialog1.SelectedValue);
ddlDialog2.DataValueField = "Id";
ddlDialog2.DataTextField = "name";
ddlDialog2.DataBind();
}
upnl.Update();
}
Problem here is,
How to Populate second drop down list(ddlDialog2) upon value change in the first drop down list.
Any idea?
You need to add the Server side change event of the 1st dropdown.
Modify the html of 1st drop down as follows.
<asp:DropDownList ID="ddlDialog1" runat="server" OnSelectedIndexChanged="upnl_Load()" />
remove jquery change and manually calling _do postback
$("#<%= ddlDialog1.ClientID %>").change(function () {
$.ajax(function{
url: "/YourPage.aspx"
type:"POST"
data:{"FirstDropDownValue" : $(this).val() }
success:function(msg){
//bind your second dropdown here.
if(msg.d != null)
{
// Looping over list
$.each(msg.d, function (index, value) {
$("#ddlDialog1").append($("<option> </option>").val(value["Id"]).html(value["name"]));
});
}
});
Update the server side method as follows
[WebMethod]
public static List<Myclass> void upnl_Load( string FirstDropDownValue)
{
if (FirstDropDownValue != "-1")
{
return objMngr.GetData(FirstDropDownValue);
}
upnl.Update();
}

Maximum checked allow in CheckBoxList

I have generated a CheckBoxList which has more than one item using C#. Now I want to set a maximum number of checked item allowed in CheckBoxList. If user check more than maximum allowed item, there will be an alert or the other item will automatic uncheck to prevent user check over maximum number of item allowed.
The maximum number of checked item will be set up to ChecokBoxList in code-behind (C#) or using javascript do this, but the javascript is also should be generated in C# too.
I need some help to solve this issue.
Example Code:
CheckBoxList chkl = new CheckBoxList();
string[] items = {"item1", "item2", "item3", "item4", "item5"};
foreach (string item in items )
{
chkl.Items.Add(new ListItem(item));
}
chkl.MaximumCheck = 3;
After generated in code-behind, the CheckBoxList will only allow user to check only three items. If user check more than three item, other item will automatic uncheck or at least an alert will show to prevent user check more than three items.
I have a good solution for this issue:
In C# I will generate a CheckBoxList with 5 items using this code:
CheckBoxList chkl = new CheckBoxList();
string[] items = { "item1", "item2", "item3", "item4", "item5" };
foreach (string item in items)
{
chkl.Items.Add(new ListItem(item));
}
chkl.AutoPostBack = true;
chkl.CssClass = "3";
chkl.SelectedIndexChanged += new EventHandler(BoxChecked);
As you can see, the CheckBoxList has 5 item and the maximum checked item is seted via CssClass attribute of CheckBoxList, assumed there will be no CssClass needed in CheckBoxList. So that I will set the maximum checked item via this attribute to make it more clear. The key here is to add an EventHandler on CheckboxList, so that if user going to check more than the maximum item, other item will be disable.
The EventHander will be written as follow:
protected void BoxChecked(object sender, EventArgs e)
{
try
{
int maximumCheck = -1;
CheckBoxList CheckExpertiseList = (CheckBoxList)sender;
try {
maximumCheck = Convert.ToInt32(CheckExpertiseList.CssClass);
}
catch { }
if (maximumCheck > -1)
{
if (CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == true)).Count() == maximumCheck)
{
CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == false)).ToList().ConvertAll(i => i.Enabled = false).ToList();
}
else if (CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == true)).Count() == maximumCheck - 1)
CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == false)).ToList().ConvertAll(i => i.Enabled = true).ToList();
}
}
catch { }
}
EventHandler Event will check if the checkboxlist has over limit item checked it will disable other items, else it will reenable other item.
int x = 0;
foreach (var li in ListBox1.Items) {
if (li.Selected == true)
{
x = x + 1;
}
or like:
ListBox1.GetSelectedIndices().Length
In Javascript:
<script type="text/javascript" language="javascript">
function CheckCheck()
{
var chkBoxList=document.getElementById('<%=CheckBoxList1.ClientID %>'); var chkBoxCount=chkBoxList.getElementsByTagName("input");
var btn=document.getElementById('<%=btnSubmit.ClientID %>');
var i=0;
var tot=0;
for(i=0;i<chkBoxCount.length;i++)
{
if(chkBoxCount[i].checked)
{
tot=tot+1;
}
}
if(tot > 3)
{
alert('Cannot check more than 3 check boxes');
}
</script>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" onclick="javascript:CheckCheck();">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
</asp:CheckBoxList>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
First of all, I am thank you to Jeremy Thompson. He gave me a good idea for my issue. A little bit change and I have what I want. Solve my issue only using javascript.
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript" language="javascript">
function CheckCheck() {
var chkBoxCount = this.getElementsByTagName("input");
var max = parseInt(this.className);
var i = 0;
var tot = 0;
for (i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked) {
tot = tot + 1;
}
}
if (tot > max) {
var k = 0;
for (i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked) {
k++;
if (k > max) {
chkBoxCount[i].checked = false;
alert('Cannot check more than ' + max + ' check boxes');
}
}
}
}
}
</script>
<div>
<table>
<tr>
<td>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="3" onclick="javascript:CheckCheck.call(this);">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
</asp:CheckBoxList>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
The javascript will automatic recognize what control is going to call it, and it also get the maximum check item via attribute CssClass of control. By doing this, I also prevent user check more than maximum item in CheckBoxList without doing some post-back.
private void cb_magia_SelectedIndexChanged(object sender, EventArgs e)
{
int maxNumber = 4;
int iSelectedIndex = cb_magia.SelectedIndex;
if (cb_magia.CheckedItems.Count > maxNumber)
{
cb_magia.SetItemCheckState(iSelectedIndex, CheckState.Unchecked);
MessageBox.Show("you had checked the maximum checkbox value allowed");
}
}

Yet another viewstate dropdownlist issue

I have the following code in the Page_Load method of a web form:
protected void Page_Load(object sender, EventArgs e)
{
CountrySelectButton.Click += new EventHandler(CountrySelectButton_Click);
if (HomePage.EnableCountrySelector) //always true in in this case
{
if(!IsPostBack)
BindCountrySelectorList();
}
}
The BindCountrySelectorList method looks like this:
private void BindCountrySelectorList()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(HomePage.CountryList);
var ds = nvc.AllKeys.Select(k => new { Text = k, Value = nvc[k] });
CountrySelector.DataSource = ds;
CountrySelector.DataTextField = "Text";
CountrySelector.DataValueField = "Value";
CountrySelector.DataBind();
}
And I have a LinkButton click event handler which gets the SelectedValue from the SelectList as so:
void CountrySelectButton_Click(object sender, EventArgs e)
{
//get selected
string selectedMarket = CountrySelector.SelectedValue; //this is always the first item...
//set cookie
if (RememberSelection.Checked)
Response.Cookies.Add(new HttpCookie("blah_cookie", selectedMarket) { Expires = DateTime.MaxValue });
//redirect
Response.Redirect(selectedMarket, false);
}
EDIT:
This is the DDL and LinkButton definition:
<asp:DropDownList runat="server" ID="CountrySelector" />
<asp:LinkButton runat="server" ID="CountrySelectButton" Text="Go" />
Resulting markup:
<select name="CountrySelector" id="CountrySelector">
<option value="http://google.com">UK</option>
<option value="http://microsoft.com">US</option>
<option value="http://apple.com">FR</option>
</select>
<a id="CountrySelectButton" href="javascript:__doPostBack('CountrySelectButton','')">Go</a>
END EDIT
ViewState is enabled but the SelectedValue property only ever returns the first item in the list regardless of which item is actually selected. I'm certain I'm missing something obvious but I can't find the problem; any help is much appreciated.
Thanks in advance.
Dave
You are correct that your issue stems from the jquery ui dialog... you can get around this by using a hidden field to record the value of the dropdownlist. Then in your code, reference the hidden field.
Front end could look like:
<div id="myModal" style="display: none;">
<asp:DropDownList runat="server" ID="SelectList" />
<asp:LinkButton runat="server" ID="MyButton" Text="Go" />
</div>
<input type="hidden" id="countryVal" runat="server" />
<a id="choose" href="#">Choose</a>
<script type="text/javascript">
$(document).ready(function () {
$('#choose').click(function () {
$('#myModal').dialog({
});
return false;
});
$('#<%= SelectList.ClientID %>').change(function () {
var country = $(this).val();
$('#<%= countryVal.ClientID %>').val(country);
});
});
</script>
Then your code behind:
var selected = countryVal.Value;
Wrap the MyButton.Click+=... statement inside (!IsPostBack) like
if(!IsPostBack)
{
MyButton.Click += new EventHandler(MyButton_Click);
BindSelectList();
}

Categories

Resources