Wednesday, October 28, 2009

jQuery Mutually exclusive checkboxes in asp.net

We often see radio buttons to implement single choices out of many in web forms. Wouldn’t it be better if we could imply ‘choose one option from many’ using checkboxes? I have implemented such mutually exclusive checkboxes in asp.net using jquery. This certainly is not any new practice. We have already seen such mutually exclusive checkboxes in asp.net ajax, and perhaps there are others also. But achieving this functionality using a lightweight javascript library like jquery would be a benefit. So let’s start the race.

First of all, let me present the design philosophy of this realization of mutually exclusive checkboxes.

1. We will have a group of checkboxes with same css class name. We will not need the id of checkboxes besides for associating label to display text and make label clickable.

2. For our example, initially we will check one of the checkboxes. You may wish not to and this will work.

3. We can add any number of such groups of checkboxes but each group will have distinct class name. For example, one group of checkboxes can have class name ‘class1’ and other can have ‘class2’ and so on.

4. When a checkbox is checked, if it is already checked nothing will happen, otherwise this checkbox will be checked and all other checkboxes having the same class name as of this checked one will be unchecked.

5. If a checkbox is unchecked, we re-check it, since we want at least one checkbox checked. We can let a checkbox get unchecked if our requirement does not demand at least one option checked, but for this tutorial we will not let so.

By this time we have realized the need and design philosophy of implementing mutually exclusive checkboxes in asp.net using jquery. Now let’s proceed on.

We need the latest version of jquery which is available here [latest version is jquery 1.3.2 till date].


Fig:1 jQuery library added in asp.net website project

Now reference the jquery library file in the head section of the design page.


Fig:2 jQuery libray referenced in the header section of asp.net design page

Here goes the design markup code in the aspx page.

<form id="form1" runat="server">
<asp:Label ID="lblResult" runat="server" ForeColor="Green"></asp:Label>
<div id="toggleContainer">
I like to mix
<input type="checkbox" id="aspnet" class="firstClass" checked="checked" runat="server"/>
<label for="aspnet">asp.net</label>
<input type="checkbox" id="php" class="firstClass" runat="server"/>
<label for="php">php</label>
<input type="checkbox" id="jsp" class="firstClass" runat="server"/>
<label for="jsp">jsp</label>
<input type="checkbox" id="asp" class="firstClass" runat="server"/>
<label for="asp">asp</label>
<br /><br /> with
<input type="checkbox" id="jquery" class="secondClass" checked="checked" runat="server"/>
<label for="jquery">jquery</label>
<input type="checkbox" id="javascript" class="secondClass" runat="server"/>
<label for="javascript">pure javascript</label>
<input type="checkbox" id="aspnetajax" class="secondClass" runat="server"/>
<label for="aspnetajax">asp.net ajax</label>
<input type="checkbox" id="thirdajax" class="secondClass" runat="server">
<label for="thirdajax">third party ajax</label>
<br /><br />
<asp:Button ID="btnResult" runat="server" OnClick="btnResult_Click" Text="Show Result!" />
</div>
</form>


Fig:3 Mutually exclusive checkboxes at initial state

As shown in the page code above, we have three different groups of checkboxes having class names firstClass and secondClass. Each group has one checkbox checked initially.

Now is the time to use and understand the jquery script in the page. Here is the complete code in the script block.

<script type="text/javascript">
$(document).ready(function(){
//toggle all checkboxes in toggleContainer div
$('#toggleContainer :checkbox').bind('change',function(){
var thisClass=$(this).attr('class');
if($(this).attr('checked'))
{
$('#toggleContainer :checkbox.'+thisClass+":not(#"+this.id+")").removeAttr('checked');
}
else
{
$(this).attr('checked','checked');
}
});
});
</script>

Explanation of jquery code snippet

1. We put all the codes that are required to run at the page load within document’s ready event handler code block, so the first line.

2. toggleContainer is the div element we put all our checkboxes. We have done this to avoid collision with other checkboxes in the page. For all checkboxes [as by :checkbox selector] within this div element we bind change event. So, the following code block will execute when any checkbox is checked or unchecked.

3. In the change event, we read the class name of the current checkbox in thisClass variable. Note that we are reading the value of attribute class [as by .attr method, used to get or set value of an attribute]

4. If this checkbox has attribute ‘checked’, this means we are checking this checkbox exclusive of others in its group. So we uncheck all checkboxes other than itself having class name of this checkbox [stored in variable thisClass]. How we achieve this- uncheck all checkboxes other than this? Answer is: using : not[itself] selector. This selector excludes the matching dom element from the result.

5. If this class has no ‘checked’ attribute, this means the previously checked chexbox has been tried to uncheck which we prevent by re-checking this checkbox since this violates our design philosophy.

That’s all.

Reading Result

Remember the Show Result button in the pages? Yeah, we will publish the result as of user’s selections. Here goes the code-behind code snippet.

//prints your choices in the result label
protected void btnResult_Click(object sender, EventArgs e)
{
string result = "Oh, you like to mix ";
if (asp.Checked)
result += "asp";
else if (aspnet.Checked)
result += "asp.net";
else if (php.Checked)
result += "php";
else
result += "jsp";

result += "
with ";

if (jquery.Checked)
result += "jquery ajax!";
else if (javascript.Checked)
result += "pure javascript ajax!";
else if (aspnetajax.Checked)
result += "asp.net ajax!";
else
result += "other third party ajax!";

result += "
";

lblResult.Text = result;
}


Fig:4 Mutually exclusive checkboxes in action

Conclusion

In this simple yet descriptive tutorial we implemented mutually exclusive checkboxes in asp.net using latest javascript jquery library. Since we used class property of checkboxes, we have been able to implement this with any number of distinct groups of checkboxes. If you enjoyed this tutorial, please spread the words: bookmark this, share your opinions via comments or email this article etcetera! Happy programming!

kick it on DotNetKicks.com

Thursday, September 3, 2009

Programming foa and fop to generate pdf files from xml and xslt

In real world, there is a great deal of demand of pdf files. Programmers often need to generate pdf file from data fed in different formats. One popular format is xml. There exists lots of ways to generate pdf files in different programming languages. And interestingly most of them are platform and program independent. Sweet!

I am currently programming xslt. There has been an interesting task. We have xml file as input and fop batch file which can be run to accept some xml, xslt and pdf files to generate pdf out of the xml and xslt file. With this scenario, all we have to do is write the xslt that styles and maps to the original xml file, which can be then rendered as pdf files.

We are writing xslt using foa. The fop can take this xslt as input. The foa even provides IDE to write xslt. And this free yet significant tool is very programmer-friendly in the sense it provides environment to integrate style and xml at once into the xslt from one place.

This is my first time with fop and foa. They do make great marriage. But there doesn't seem to be updates in foa since long time. The latest foa we get is too old to match the latest version of fop. How would this foa keep with the latest, new, improved fop?

Anyway, I hope to come up with more issues in using xsl. Keep up warming your programming. Happy programming!

Wednesday, August 12, 2009

International Youth Day 2009

Hi all. Today is August 12, 2009, the International Youth Day. May this day empower the youth all over the world!

Monday, August 10, 2009

Smart sorting, paging in asp-net, especially repeater control

Hi all. There has been little lagging in my presence to you all with new post. Actually these days there are lots of things in my mind. I am looking over the web to know the best asp.net performance practices. But most of the times I do get stuck with the same old strategies you can find everywhere if you search with the keyword – "asp.net performance tips" or so. However, these tips work 90% of the cases, they are intermediate ones. What about the advanced ones? There are some genius guys who have presented advanced and deep asp.net performance improvement techniques, and thanks to them. Good things cannot hide, so you are sure to find them over the web hanging here and there, no problem.


But here I am going to talk about one thing- paging and sorting in asp.net. From the very beginning I am dissatisfied with the old, easy paging of asp.net gridview that really kills the spirit of web- faster response and scalability. In fact gridview and datagrid both generate heavy markup. The only good way to get rid of all these is to do custom paging, sorting with the gridview and datalist.

Then what about repeater control? Yes, the best option to go is use repeater and use custom sorting/paging with it. Repeater control has always won the heart of programmers- light, efficient and thus effective! I have just been through this better way of paging and sorting with asp.net gridview control. They have managed an example page also. I hope following the same pattern would make a good impression with repeater control also. We would certainly go different pattern for sorting- perhaps a dropdownlist populating all the column names and another dropdownlist with "asc" and "desc" for sorting direction.

As alternatives, I have also liked: this one from codeproject and this one discussed in asp.net tutorial.

What you think? I am still looking for the best paging in asp.net- for gridview, datalist or repeater. Your suggestions and referrals are welcome. Please keep in mind that I am fond of performance friendly options. Thank you. Happy Programming!

kick it on DotNetKicks.com

Friday, July 3, 2009

How to change second textbox text when the first textbox date of AJAX CalendarExtender changes?

Sometime ago I saw an interesting question in asp.net forum. It raised my enthusiasm. I started to code the requirement. And I found one. Here goes the requirement:

Hi!

I have two text boxes inside my aspx page: a) the "txt1" and b) the "txt2". Both text boxes have CalendarExtender controls attached:
a) the txt1 has the "CalendarExtender1"
b) the txt2 has the"CalendarExtender2".

All I want is this:
Using client-side script (or other method without postbacks), I want when the user chooses a date from CalendarExtender1, the same date plus a day front to go to the txt2.

For example:
If the user chooses 03/28/2009 in the CalendarExtender1, I want the value of the txt2 to be the 03/29/2009....
Also, if the month reaches the end, I want the txt2 to take the new moth.

For example:
If the user chooses 03/31/2009 in the CalendarExtender1, I want the value of the txt2 to be the 04/01/2009....

That behavior I want to exists only to the CalendarExtender1 like I describe it. I don't want the user to be able to do this with CalendarExtender2 (the CalendarExtender2 has the default behavior)...

How can I accomplish that? Thank you very much!

There are two solutions provided to this requirement. Let me put them here.

Solution1: (By Kinjalin)

Here you have to add it in Javascript.

<cc1:CalendarExtender ID="ClExFromDt"                     runat="server"                     TargetControlID="TxtFromDate"                     PopupButtonID="BtnFromCal"                     Format="dd/MM/yyyy"                     OnClientDateSelectionChanged="AddDate"                     CssClass="calExt_Theme1"></cc1:CalendarExtender>

Here on OnBlur, write a Javascript function addDate

on Page_Load write the line " Text1.Attributes.Add("onblur", "javascript:addDate();")

& in Javascript Fetch the Value using document.getElementByID("TextBox1").value

add it using below Javascript & bit of ur Logic

//create the date
var myDate = new Date();


//add a day to the date
myDate.setDate(myDate.getDate() + 1);


//add a week
myDate.setDate(myDate.getDate() + 7);

After adding Show it in your TextBox2

$get(TextBox2).value = myDate

Thats it.

Solution2: (By sangam100)

Hi MinimalTech ,

Here goes the prototype, which is close to what kinjalin posted:

Add this script in the design page:

<script>

function addDays() {

dateParts = document.getElementById('txtDate1').value.split('/');

year = dateParts[2];

month = parseInt(dateParts[0])-1;

day = parseInt(dateParts[1]) + 1;



newDate = new Date ( year, month, day );

year = newDate.getYear();

month = newDate.getMonth()+1;

day = newDate.getDate();

formattedDate = month + '/' + day + '/' + year;



document.getElementById('txtDate2').value=formattedDate;

}

</script>

Now in the design page:

Date1:<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>  Date2 (One day forward):<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox><cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate1" PopupButtonID="txtDate1"></cc1:CalendarExtender>

In the code behind.

txtDate1.Attributes.Add("onchange", "addDays();");

Now this works.

Hope this will be useful to all. Happy Programming!

Popular Posts

Recent Articles