ASP.NET and C#.
I'd like to have a CheckboxList with a "Select All" item.
When this particular item is
selected, all others will be selected
too.
When selection is removed from
this item, so too will it be from all
others items.
Checking/Unchecking of
any other items will only have an
effect on that particular item
regardless of the selection state of
"Select All" item.
I am looking for a jquery solution to this.
Here is the databinding code in my codebehind:
IList<Central> Centrals = new CentralProvider().GetAllCentralsAsList();
Centrals.Insert(0, new Central(){Central_ID = 999, Central_Name = "Select All"});
CentralChecks.DataSource = Centrals;
CentralChecks.DataTextField = "Central_Name";
CentralChecks.DataValueField = "Central_ID";
CentralChecks.DataBind();
And here is the markup:
<div class="CentralDiv" id="CentralDiv">
<h2>Centrals:</h2>
<span>
<asp:TextBox ID="CentralTextBox" runat="server" CssClass="textbox">Centrals</asp:TextBox>
<img id="CentralArrow" src="images/down_arrow.jpg" style="margin-left: -22px; margin-bottom: -5px" />
</span>
<div id="CentralEffect" class="ui-widget-content">
<asp:CheckBoxList ID="CentralChecks" runat="server" onclick="GetSelectedCentralValue();">
</asp:CheckBoxList>
</div>
</div>
Note that there are multiple checkbox lists on the page, so any solution must keep this in mind.
Something like you could use for any of your checkbox lists, just add a cssclass of myCheckBoxList to each CheckBoxList control:
$('.myCheckBoxList :checkbox').eq(0).click(function() {
var toggle = this.checked;
$('.myCheckBoxList :checkbox').attr("checked", toggle);
});
You can iterate through all ListItems on click of Select All. And maintain a state flag to maintain whether all checkboxes are checked or not
if(boolAllChecked) {
foreach (ListItem listItem in CentralChecks.Items)
{
listItem .Selected = false;
}
}
else {
foreach (ListItem listItem in CentralChecks.Items)
{
listItem .Selected = true;
}
}
here is an example: http://jsfiddle.net/VTgGA/
code:
$('input:checkbox').click(function(){
var $this = $(this);
if($this.attr('ref') != 'checkall'){
$(".select-all").attr('checked',false);
}
else {
//Select All
var $checked = $this.is(':checked');
$('input:checkbox').each(function(){
$(this).attr('checked',$checked);
})
$(".select-all").attr('checked',$checked);
}
})
this is what the html of the checkboxes:
<input type='checkbox' ref='checkall' class='select-all'/>
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
Extending mdmullinax's brilliant answer, I came up with this generic solution for "select all" behavior that also unticks the "select all" (i.e. first) option if any other option is unticked and reticks the "select all" when all other items are ticked.
It also executes on window load as I inject it from ASP.Net server-side controls (which inject script in the head section of the page). Better to be safe than sorry :)
$(window).load(function () {
var cbs = $('.myCheckBoxList :checkbox');
cbs.eq(0).click(function () {
var toggle = this.checked;
cbs.attr('checked', toggle);
});
cbs.slice(1).click(function () {
if (!this.checked) {
cbs.eq(0).attr('checked', false);
} else {
cbs.eq(0).attr('checked', cbs.slice(1).filter(':not(:checked)').length == 0);
}
});
});
There is a generic way of having a select all item in asp CheckBoxList with using jquery.
You can have as many as CheckBoxList controls on the form with the select all functionality.
you only need to make sure
Your CheckBoxList has allowSelectAll Class
You added a ListItem to your checkbox list to allow users to select
All with the value of All
chkBoxList.Items.Insert(0, new ListItem("All", "All"));
you Only need the following code
<script>
$('.allowSelectAll :checkbox[value=All]').click(function () {
var toggle = this.checked;
$(this).closest('.allowSelectAll').find(":checkbox").attr("checked", toggle);
});
</script>
In the following code spinet I have 4 Checkbox lists
<div >
<label>Experience 1</label>
<asp:CheckBoxList ID="chklstExp1" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 2</label>
<asp:CheckBoxList ID="chklstExp2" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 3</label>
<asp:CheckBoxList ID="chklstExp3" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Location</label>
<asp:CheckBoxList ID="chklstLocation" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<asp:Button runat="server" ID="btnShowReport" OnClick="btnShowReport_Click" Text="Show Report"/>
</div>
Related
I have been trying to create a radio button that shows/hides the two drop-down lists when they are unchecked and checked.
My problem is that whenever I try to check another radio button, the drop-down list for the other radio button does not hide as intended. For example, if I checked rbtnTwocolor, the drop-down list for rbtnOnecolor does not hide.
I wanted to use radio button list but I couldn't insert a drop-down list in between the radio button list items.
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>
for show/hide dropdown when select radiobutton , you can use ways below :
1: use jquery in client side:
<script>
$(document).ready(function () {
$('#rbtnTwoColor').change(
function () {
if ($(this).is(':checked')) {
$('#twocolor').show();
$('#onecolor').hide();
}
});
$('#rbtnOneColor').change(
function () {
if ($(this).is(':checked')) {
$('#onecolor').show();
$('#twocolor').hide();
}
});
});
</script>
2: use server side event (OnCheckedChanged):
markup:
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor"runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnTwoColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnOneColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>
and code behind:
protected void rbtnTwoColor_CheckedChanged(object sender, EventArgs e)
{
ddlTwoColor.Visible = true;
ddlOneColor.Visible = false;
}
protected void rbtnOneColor_CheckedChanged(object sender, EventArgs e)
{
ddlOneColor.Visible = true;
ddlTwoColor.Visible = false;
}
3: use javascript in client side:
add below code to rbtnTwoColor radiobutton
onclick="twoColorClick()"
add below code to rbtnOneColor radiobutton
onclick="oneColorClick()"
now in end of body tag add this code
<script>
function oneColorClick() {
document.getElementById('onecolor').style.display = 'block';
document.getElementById('twocolor').style.display = 'none';
}
function twoColorClick() {
document.getElementById('twocolor').style.display = 'block';
document.getElementById('onecolor').style.display = 'none';
}
</script>
good luck
In my project, i've been trying something for a while. User must select the Group from select. This Add button runs asp repeater so i can list groups. There are 2 button in group line. Right one delets the group and left one opens dynamic divs. (As you can see) There are some Javascript works so i set the id's dynamically. It's ok until here. Now, if the user want to check fixed questions, i need to show the questions that in that group. And user must be able to add question under the group dynamically. I tryed to use GridView but i couldnt handle. So any advice?
Here is what i want to do:
<ul>
<asp:Repeater ID="GroupRepeater" runat="server">
<ItemTemplate>
<li class="groupli">
<div style="width:100%; float:left; margin-top:2%;">
<h3 style="display:block; float:left; width:auto;"><%# Container.ItemIndex+1 %>.<%# Eval("QuestGroup")%></h3>
<asp:Button CssClass="GroupLiButtonD" OnClick="RemoveGroup" CommandArgument='<%# Eval("QuestGroup") %>' ID="DeleteGroupBtn" runat="server"/>
<button type="button" onclick="ShowQuestArea('<%# Container.ItemIndex+1 %>_div')" class="GroupLiButtonA"></button>
</div>
<div id='<%# Container.ItemIndex+1 %>_div' style="width:100%; margin-left:3%; float:left; display:none;">
<div class="questarea">
<div style="width:100%; margin-top:1%;">
<h4 style="display:block; float:left; width:200px;">Add Fixed Question</h4>
<input name='check_<%# Container.ItemIndex+1 %>' id='fixcheck_<%# Container.ItemIndex+1 %>' onchange="FixedCheck('fixcheck_<%# Container.ItemIndex+1 %>','<%# Container.ItemIndex+1 %>')" type="radio" />
</div>
<div id="fixarea_<%# Container.ItemIndex+1 %>" class="subarea"> <%--fixedquestion view start tag--%>
</div> <%--fixedquestion view end tag--%>
<div style="width:100%; margin-top:1%;">
<h4 style="display:block; float:left; width:200px;">Add Random Question</h4>
<input name='check_<%# Container.ItemIndex+1 %>' id='randomcheck_<%# Container.ItemIndex+1 %>' onchange="RandomCheck('randomcheck_<%# Container.ItemIndex+1 %>','<%# Container.ItemIndex+1 %>')" type="radio" />
<div id="randomarea_<%# Container.ItemIndex+1 %>" class="subarea">
<div style="margin-top:1%;">
<p style="color:black; float:left;">Number of Random Questions:</p><input type="number" max="20" min="0" style="width:20px; float:left;" />
<button>Add</button>
</div>
</div>
</div>
</div>
</div>
</li>
</ItemTemplate>
</asp:Repeater>
</ul
My code might seem complicated. I added an image. So you can ignore my code for giving advice. Thank you.
Maybe a bit of jquery and some ajax calls will do the trick.
You can add same class and a data-groupid attribute to the "fixed answer" radio buttons.
Lets say the id of the group questions is resultlist and it is a ul element.
Then you will handle the click to load the questions with ajax
$(".yourclass").on"click", function (e) {
var groupid=$(this).data("groupid");
//get the questions
$.ajax({
type: 'POST',
contentType: "application/json; charset=iso-8859-7",
url: 'yourpage.aspx/yourmethod',
data: "{'group':'" + groupid +"'}",
async: false,
error: function (xhr) {console.log(xhr.responseText);},
success: function (response) {
//Query the jQuery object for the values
var items = response.d;
if (items == null) {
$('#resultlist').empty();
$('#resultlist').append("<li> no questions... </li>");
}
else {
var fragment = "";
$.each(items, function (index, val) {
var theQuestion = val.theQuestion;
var theCode = val.theCode;
fragment += "<li data-qustionid='"+theCode+"' class='question'>"+theQuestion+"</li>";});
$('#resultlist').empty();
$("#resultlist").append(fragment);
}
});
});
in your .cs file you will add a new web method that will get the group's questions
[WebMethod]
public static List<Results> yourmethod(string text, string phone, string type)
{
List<Results> result = new List<Results>();
DataTable question = getQuestions();
if(question!=null){
foreach (DataRow rw in autocomlete.Rows)
{
result.Add(new Results { theQuestion = rw[0].ToString(),
theCode = rw[3].ToString() });
}
}
return result;
}
and likewise you will handle the click of the class question which on click will get the data-questionid and update it to the database. You can add more fields that you need in the data- attributes (link here) Readmore for ajax here
I have a repeater with 1 checkbox for every item. I want to only have one checked at a time.
The checkboxes is asp:checkbox, don't know if it makes any difference.
I tried with some jquery but it doesn't seem to work.
<asp:Repeater runat="server" DataSourceID="SqlDataSource1" ID="repeater1">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" Checked='<%# Eval("carousel_check")%>'/>
</ItemTemplate>
</asp:Repeater>
I have tried to give the checkbox a cssclass (checked_button) and then this script.
$(document).ready(function () {
$('.checked_button').change(function () {
if ($(this).is(':checked')) {
$('.radio-similar').not(this).removeAttr('checked');
};
});
});
ASP.Net Checkbox is rendered inside span tag.
<span class="checked_button">
<input id="MainContent_Repeater1_CheckBox1_2"
type="checkbox" name="ctl00$MainContent$Repeater1$ctl02$CheckBox1">
</span>
So the selector should be .checked_button input. Then uncheck all checkboxes, and check only the one triggered the click event.
$(function() {
$(".checked_button input").click(function () {
$('.checked_button input').attr("checked", false);
$(this).prop("checked", true);
});
});
I have a issue. I have an asp.net webform which has a process which stores the data in a session. The issue I can't resolved is that on one of the pages it displays all the details entered throughout the process but one section in only needed to be displayed depending on the selection from my checkboxlist.
HTML for my checkboxlist
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList">
<asp:ListItem Text="All services" Value="All services"></asp:ListItem>
<asp:ListItem Text="Site content uploading only" Value="Site content uploading only"></asp:ListItem>
<asp:ListItem Text="Site content & layout checking" Value="Site content & layout checking"></asp:ListItem>
<asp:ListItem Text="Testing on various browsers" Value="Testing on various browsers"></asp:ListItem>
<asp:ListItem Text="Testing all website functionality" Value="Testing all website functionality"></asp:ListItem>
<asp:ListItem Text="Responsive design (Design/Implemtation only)" Value="Responsive design (Design/Implemtation only)"></asp:ListItem>
<asp:ListItem Text="Responsive design (Testing only)" Value="Responsive design (Testing only)"></asp:ListItem>
</asp:CheckBoxList>
Code behind for the above which stores the selections in the session
private void SessionSaving()
{
List<string> selections = new List<string>();
foreach (ListItem listItem in Services.Items)
{
if (listItem.Selected)
{
selections.Add(listItem.Value);
}
}
Session["Step02Services"] = selections;
}
HTML for my confirmation page
<div class="form-group">
<asp:Label ID="Step04BrowsersLabel" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Browser(s) to check on:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<%= string.Join(", <br />",((List<string>)Session["Step04Browsers"]).ToArray()) %>
<% if (Session["Step04OtherField"] != "")
{%>
<br />
<%=Session["Step04OtherField"] %>
<%} %>
</div>
</div>
I don't want the above section to be displayed if any of the following scenarios checked checkboxes happen:
Site content uploading only
Site content & layout checking only
Site content uploading & Site content & layout checking only
I tried the following if, and it doesn't always displays for me. If I remove the ||'s and just use the first line it hides it for me. If I select the "Site content uploading only" checkbox and another checkbox it also displays if for me (which is correct).
if (string.Join("", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking"
|| string.Join(", <br />", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking"
|| string.Join("", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking" && string.Join(", <br />", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking")
How do I write/correct my if above?
My fix was to the HTML on the confirmation page as shown below
if (Session["Step04Browsers"] != null)
{
<div class="form-group">
<asp:Label ID="Step04BrowsersLabel" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Browser(s) to check on:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<%= string.Join(", <br />",((List<string>)Session["Step04Browsers"]).ToArray()) %>
<% if (Session["Step04OtherField"] != "")
{%>
<br />
<%=Session["Step04OtherField"] %>
<%} %>
</div>
</div>
}
I must of had some major brain fart yesterday as this morning it was clear as day. For some reason when i posted this post i was looking at a selction made from my services checkboxlist when infact all i had to do was look at my browser checkboxlist on another page. If it was empty dont display otherwise display it. Can't belive i didnt think of this yesterday.
Wrapped the div in:
if (Session["Step04Browsers"] != null)
You don't even need to store anything in the session you can do this all client side. To get the selected list items you can use:
var checked_checkboxes = $("#<%= Services.ClientID %> input:checked")
Then you can get the value and text as so:
checked_checkboxes.each(function() {
var value = $(this).val();
var text = $(this).closest("td").find("label").html();
}); /* You can also use a for loop */
I suggest changing
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList">
to
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList" onclick="ChangeCheckBox();">
where ChangeCheckBox is a javascript function that gets the selected values as shown above and then hides/shows the div based on what values are selected.
I have a C# list:
List<string> Listtags = GetListTag.GetTagList().ToList();
And, I would like to put it into a Div:
<div id="tags">
<ul>
<li><This should be populated with my list></li>
//This list can have any number of items depending on how big my list tags is
</ul>
</div>
Could someone show me how to do this?
you can also use Repeater
<ul>
<asp:Repeater runat="server" id="R">
<ItemTemplate>
<li><%# Container.DataItem %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
and in runtime
List<string> ListTags = GetListTag.GetTagList().ToList();
R.DataSource = ListTags;
R.DataBind();
Use asp:bulletedList and your list will be much easier.
<div id="tags">
<asp:BulletedList id="blTabs"
BulletStyle="Disc"
DisplayMode="LinkButton"
runat="server">
</asp:BulletedList>
</div>
Code Behind:
ListItem li = new ListItem();
li.Value = "html text"; //html goes here i.e. xtab1.html
li.Text = "New Text"; //text name goes i.e. here tab1
blTabs.Items.Add(li);
If you're using ASP.NET, you could use a BulletedList webserver control:
<asp:BulletedList ID="BulletedList1" runat="server"
BulletStyle="Circle"
DisplayMode="Text">
</asp:BulletedList>
and in codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> Listtags = GetListTag.GetTagList().ToList();
Listtags.ForEach(t => BulletedList1.Items.Add(t));
}
}
Edit: "I want to add something like this::: Listtags.ForEach(t => BulletedList1.Items.Add(t),"$tag$ "); weight being a variable in my code"
So i assume that you want to add hyperlinks and apply a different css class on the items.
<asp:BulletedList ID="BulletedList1" runat="server"
CssClass="TagList"
DisplayMode="HyperLink">
</asp:BulletedList>
and for example the css:
<style>
.TagList a {text-decoration:none}
.TagList a:link {text-decoration:none}
.TagList a:visited {text-decoration: none; color: blue}
.TagList a:hover {text-decoration: underline; color: red}
</style>
and how you add the links dynamically(the value of the ListItem is the URL):
Listtags.ForEach(t =>
BulletedList1.Items.Add(new ListItem(t, browseUrl + "?tag=$urlencodetag$"))
);
If you are using MVC3 you can do something like the following:
<div id="tags">
<ul>
#foreach(var item in Model.Listtags)
{
<li>#item.YourPropertyName</li>
}
</ul>
</div>
In Asp.Net
<ul id = "myul" runat = "server">
</ul>
In Code Behind (In Page Load I suppose or button click)
Listtags.ForEach(x => new ListItem(){Text = x });