Check All Checkbox In GridView To Bulk Edit Or Update ASP.NET C# VB.NET

In this example i am going to describe how to implement CheckAll CheckBox in GridView to check all the rows in gridView.

For this i have put a checkBox in header Template of gridview which on checking will check all the rows in gridview using server side code.



Html Source of gridView

<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="false"
CellPadding="2" ForeColor="#333333"
GridLines="Both"
DataKeyNames="ID"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll"
>
<
HeaderTemplate
>
<
asp:CheckBox ID="chkSelectAll" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged"
/>
</
HeaderTemplate
>
<
ItemTemplate
>
<
asp:CheckBox ID="chkSelect" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate
>
</
asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate
>
<
asp:TextBox ID="txtName" runat="server"
Text='<%# Bind("Name") %>' ForeColor="Blue"
BorderStyle="none" BorderWidth="0px"
ReadOnly="true"
>
</
asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server"
Text='<%# Bind("Location") %>'
ForeColor="Blue" BorderStyle="none"
ReadOnly="true">
</asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField
>
</
Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]"
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)"

UpdateCommand
="UPDATE [Details] SET [Name] = @Name,
[Location] = @Location WHERE [ID] = @ID"
>
<DeleteParameters
>
<
asp:Parameter Name="ID" />
</DeleteParameters
>

<
UpdateParameters
>
<
asp:Parameter Name="Name" />
<asp:Parameter Name="Location"
/>
<
asp:Parameter Name="ID"
/>
</
UpdateParameters
>
</
asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server"
OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server"
OnClick="btnDelete_Click"
Text="Delete" />
C# Code behind

protected void chkSelectAll_CheckedChanged
(object sender, EventArgs e)
{
CheckBox chkAll =
(CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = false;
txtlocation.ReadOnly = false;
txtname.ForeColor = System.Drawing.Color.Black;
txtlocation.ForeColor = System.Drawing.Color.Black;
}
}
else
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = true;
txtlocation.ReadOnly = true;
txtname.ForeColor = System.Drawing.Color.Blue;
txtlocation.ForeColor = System.Drawing.Color.Blue;
}
}
}
VB.NET code behind
Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"),CheckBox)
If chkAll.Checked = True Then
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"),CheckBox)
chkSel.Checked = True
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = False
txtlocation.[ReadOnly] = False
txtname.ForeColor = System.Drawing.Color.Black
txtlocation.ForeColor = System.Drawing.Color.Black
Next
Else
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
chkSel.Checked = False
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = True
txtlocation.[ReadOnly] = True
txtname.ForeColor = System.Drawing.Color.Blue
txtlocation.ForeColor = System.Drawing.Color.Blue
Next
End If
End Sub

If you have better solution, just tell me !

Ajax Autocomplete textbox add progress Image using javascript

In this example i m going to describe how to add animated Progress Image inside Ajax Auto complete extender textbox to represent loading of data.

For achieving this functionality i am using two different approaches for different versions of AjaxControlToolkit.dll


1st Approach

This approach is very simple and can be handy if you are using older/earlier version of AjaxControlToolkit (eg versions like 1.0.10201.0) which does not support css properties or properties like onclientpopulating. For this write the below mentioned javascript in head section of html markup of the aspx page.

<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';

document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';

document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>

In this script I've written two function to show and hide image, in the functions i m setting the background image style using document.getElementByID method , Now write this code in Page_Load event of aspx page.

protected void Page_Load(object sender, EventArgs e)
{
this.txtAutoComplete.Attributes.Add
("onkeypress", "ShowImage()");
this.txtAutoComplete.Attributes.Add
("onblur", "HideImage()");
}

Here i've added onblur and onkeypress attributes to textbox and calling respective function of javascript to show hide image.Build the solution and run ti see the results.


2nd approach

This approach works if you are using newer versions of AjaxControlToolkit.dll (Version 1.0.20229.20821 or later)
For this write the above mentioned javascript in head section of html markup of page.
Now in source of autocomplete extender add onclientpopulating="ShowImage" and onclientpopulated="HideImage".

<ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>

Complete html source of the page look like


<head runat="server">
<title>

Progress Image in AutoComplete TextBox

</title>
<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';

document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';

document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>
</head>
<body>
<
form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</
asp:ScriptManager>
<
br />
<
div>
<
asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</
asp:TextBox><br />
<
ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>

If you have better solution, just tell me !

Adding and using jQuery on Blogger / Blogspot

Investigating my visitors statistics, I noticed that there were some users who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you have to do is to add one line of code to your template’s header.

Here is the code to add to your blogger template’s header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6
/jquery.min.js" type="text/javascript"
></script>
NOTE:

You don’t even need to upload jquery.js file on any other hosting Google will host it for your.

Instruction for adding jQuery to Blogger:

Login to your dashboard;
Choose your blog;
From the top menu select “Layout”;
Then select “Edit HTML” sub-menu;
Add the above code just below tag (or alternatively, just above tag)

If you have better solution, just tell me !

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem

Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.

The solution:

// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
// Minimized code, suggested by Kovacs
$('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);

If you have better solution, just tell me !

Problems with jQuery mouseover / mouseout events

Today I have a quick note for you that will probably save you time someday. Basically it’s a workaround for a bug when you have parent element with children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.

The problem:
When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.

The solution:
The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.

The reason:
This solution works because mouseover and mouseout events do not bubble from child to parent element.

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

How fast jQuery’s .each() method is?
How does it compare to javascript’s native for loop?
It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
for( i=0; i < myArray.length; i++){
myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size Time
========== ======

10,000 7ms
100,000 62ms
1,000,000 613ms


jQuery .each() loop

Array size Time
========== ======

10,000 10ms
100,000 177ms
1,000,000 1100ms

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Dynamically adding table row count number using JavaScript and jQuery

Recently on jQuery mailing list a user asked how he/she could add a row count in their table automatically. So I wrote a code snippet which looks like this:

$(document).ready(function(){
$("table").each(function(){
if($(this).is('table')){
$('thead th:first-child, thead td:first-child', this).each(
                                                   function(){
if($(this).is('td'))
$(this).before('<td>#</td>');
else if($(this).is('th'))
$(this).before('<th>#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
});

This code was for specific case, where there is only one table on the page and it has only one row in its header. That is why I took into the account the possibility of row spans and multi line rows in header and rewrote the code. Then made a plugin out of it. So, here is the final code:

function($){
$.fn.extend({
addCount: function() {
return $(this).each(function(){
if($(this).is('table')){
$('thead th:first, thead td:first', this).each(function(){
if($(this).is('td'))
$(this).before('<td rowspan="'+$('thead tr').length+'">#</td>');
else if($(this).is('th'))
$(this).before('<th rowspan="'+$('thead tr').length+'">#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
}
});
})(jQuery);

To apply it to your tables use this code:

$('table').addCount();
$('.some-table-class').addCount();
$('#some-table-id').addCount();

If you have better solution, just tell me !

QR Code (generator) plugin for jQuery & JavaScript

I recently came across a 2 dimensional barcode called QR Code. QR code’s are popular in Japan and they are mainly used there to quickly get to some website on their mobiles by simply taking a picture of the QR code. You may read more about QR codes on Wikipedia.

Here is an example of QR code for jQuery HowTo blog:

If you have a QR code reader on your mobile take a picture of it and it will open this website. Cool ha?!

Anyway, there are plenty of free online QR code generator sites, but no JavaScript and jQuery plugins/functions. So, I quickly searched for a free online QR code generator sites with “friendly” URL’s and put together a javascript and jQuery functions that generate QR barcode image’s URL for passed URLs. I used Kaywa & University of Bath services.

Here are javascript and jQuery QR code functions:

// JavaScript function
function qrcode(url, size){
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) {
$.fn.qrcode = function(url, size) {
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');

The code above utilizes Kaywa’s online QR code generator. You can specify image site as the second argument to the function. The size argument mut be between 1 and 40 and the generated image will 32 x your argument.

Here is javascript and jQuery code for University of Bath barcode generator:

// JavaScript function
function qrcode(url){
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) {
$.fn.qrcode = function(url) {
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');
If you have better solution, just tell me !

Cross domain AJAX querying with jQuery

This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem.

Using this method for cross site scripting you will be able to:
Make AJAX queries to any domain even those that differ from your own;
Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery AJAX functions as your query method.

But all these does not come free, you will need to put a proxy to between you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one of my projects.


The PHP script to use as a cross domain scripting proxy:

<?php
// Set your return content type
header('Content-type: application/xml');

// Website url to open
$daurl = 'http://feeds.feedburner.com/jQueryHowto';

// Get that website's content
$handle = fopen($daurl, "r");

// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:

$("#rssFeeds").load("path/to/proxy.php", function(){
// Some callback functions
});
And this is how I overcame the jQuery cross site scripting problems. The bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request. My web server was very strict on security but the script above worked well on it.

If you have better solution, just tell me !

Remove table row on user click

This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that table row is clicked.

jQuery code to delete clicked table row came out to be surprisingly short, only 3 lines of code.

// Select all table cells to bind a click event
$('table td').click(function(){
$(this).parent().remove();
});

Here, we are first selecting all table cells to bind our click event. On user click to any table cell click event fires. In the click event we are removing ’s parent, which is , thus removing whole row.

By popular user demand I’m including an example that lets deleting a table row on delete image click. Here is our HTML table:

<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<
/table>

Here is jQuery code to delete a row on delete image click:

$('table td img.delete').click(function(){
$(this).parent().parent().remove();
});
See demos Click here.

Bonus: Also delete a table row from database

The code above is enough if you don’t need to also delete a record from your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.

$('table td').click(function(){
$.get('deleteRow.php', {id: $(this).parent().attr('id')},
function(){
$(this).parent().remove();
});
});

In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.

If you have better solution, just tell me !

Using jQuery For The Animation

The animation is really quite simple. We’ll use jQuery to animate the opacity of the <span> tag. Remember that the <span> tag displays the “hover” state of the image. Hence, when the <span> is visible, the link takes the “hover” appearance. We’ll need the “hover” state to be invisible when the page loads. We can do this by setting the opacity of the <span> tag to “0″:

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// the rest of the code will go here

});

Placing the code inside of “$(function() { … });” tells the browser to execute the code when the document has loaded. The code that we’ll use to do the animation is as follows:

// on mouse over
$("ul#menu span").hover(function () {

// animate opacity to full
$(this).stop().animate({
opacity: 1
}, 'slow');

},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({

opacity: 0
}, 'slow');
});

Hence the entire Javascript used is as follows:

<!-- Include jQuery Library -->

<script src="jquery-1.2.2.pack.js" type="text/javascript"></script>
<!-- Let's do the animation -->
<script type="text/javascript">

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, "slow");
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
</script>

Notice that we first include the jQuery library. You can learn more about jQuery animations by reading up on the documentation. One final addition to the CSS is required to ensure that the mouse cursor is display as a pointer when hovering over the <span> tag:

ul#menu li a span:hover {
cursor:pointer;

}

The full source code can be accessed via the demonstration page. I should just add that whilst this code seems to work well with FireFox and IE7, IE6 might (and probably will) be a different story.

If you have better solution, just tell me !

Ajax Triple Dropdown with States Cities Database

Ajax Dropdown Menu it's make easy for user to use interface. When you choose first dropdown menu data in second dropdown will be filter and data related in first dropdown will be show automatic

For This Example Code is PHP and Database is MySQL

Example : Stated and Cities

1. Create Dropdown Menu (state_dropdown.php)

<?
echo "<form name=sel>\n";
echo "States : <font id=states><select>\n";
echo "<option value='0'>============</option> \n" ;
echo "</select></font>\n";

echo "Cities : <font id=cities><select>\n";
echo "<option value='0'>=== none ===</option> \n" ;
echo "</select></font>\n";
?>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "state.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
window.onLoad=dochange('states', -1); // value in first dropdown
</script>
2. Select States and Cities to Show in Dropdown (state.php)

<?
//set IE read from page only not read from cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("content-type: application/x-javascript; charset=tis-620");
$data=$_GET['data'];
$val=$_GET['val'];
//set database
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");
if ($data=='states') { // first dropdown
echo "<select name='states' onChange=\"dochange('cities', this.value)\">\n";
echo "<option value='0'>==== choose state ====</option>\n";
$result=mysql_db_query($dbname,"select `id`, `state` from states order by `state`");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;

}
} else if ($data=='cities') { // second dropdown
echo "<select name='cities' >\n";
echo "<option value='0'>====choose cities ====</option>\n";
$result=mysql_db_query($dbname,"SELECT `id`, `city` FROM cities WHERE `state_id` = '$val' ORDER BY `city` ");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}
echo "</select>\n";
?>

2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)



Ex 2: This is Triple Ajax Dropdown Menu - Province - Ampher - Tumbon in Thailand

<? echo "<form name=sel>\n"; echo "จังหวัด : <font id=province><select>\n"; echo "<option value='0'>============</option> \n" ; echo "</select></font>\n";
echo "อำเภอ : <font id=amper><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; echo "ตำบล : <font id=tumbon><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; ?>

<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //รับค่ากลับมา
}
}
};
req.open("GET", "locale.php?data="+src+"&val="+val); //สร้าง connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=tis-620"); // set Header
req.send(null); //ส่งค่า
}
window.onLoad=dochange('province', -1);
</script>
2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)


<?
//IE page cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("content-type: application/x-javascript; charset=tis-620");
$data=$_GET['data'];
$val=$_GET['val'];
//ค่ากำหนดของ ฐานข้อมูล
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");
if ($data=='province') {
echo "<select name='province' onChange=\"dochange('amper', this.value)\">\n";
echo "<option value='0'>==== เลือก สังกัด ====</option>\n";
$result=mysql_db_query($dbname,"select loc_code,loc_abbr from location where loc_name = location_name and loc_code != '000000' and flag_disaster is null order by loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='amper') {
echo "<select name='amper' onChange=\"dochange('tumbon', this.value)\">\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,2);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr ");

while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='tumbon') {
echo "<select name='tumbon' >\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,4);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr, loc_name, location_name FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}

echo "</select>\n";
?>
 


PS. In ajax-dropdown.rar file Include
for states and cities (america)
state.php
state_dropdown.php
state.sql (MySQL)

for province ampher tumon (thailand)
locale.php
locale_dropdown.php
location.sql
(MySQL)

If you have better solution, just tell me !

CSS Gradients in Action

Chris Williams has been having some fun with CSS gradients on a quest to create nice looking elements without images.

He uses CSS like this:


  1. .albumInfo {
  2. background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#626262), to(#000000), color-stop(.5, #202020), color-stop(.5, #000000));
  3. height: 8em;
  4. padding: 1em;
  5. border-top: 1px solid #858585;
  6. border-bottom: 1px solid #505050;
  7. }
  8. .albumInfo h1 {
  9. font-weight: bold;
  10. text-shadow: 0px -1px 1px black;
  11. font-size: 1.2em;
  12. }
  13. ul.tracks {
  14. background: -webkit-gradient(radial, 50% -70, 0, 50% 0, 200, from(#595959), to(#0d0d0d)) #0d0d0d;
  15. width: 25.7em;
  16. }
  17. ul.tracks li.odd {
  18. background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(255,255,255,.05)), to(rgba(255,255,255,.05)));
  19. }

This example demonstrates the power of WebKit’s implementation of gradients in css. This similar looking display to that of the iPhone album display uses a radial gradient (opposed to a linear) as the background for the track names. The overall effect is a dim light. The odd numbered tracks also use a gradient to take advantage of -webkit-gradient’s support of alpha values.

None of the gradients will work in other browsers. Check that your background and text are not the same color. The outermost div is set to black so it's viewable in other browsers.

Sheer Heart Attack is my favorite Queen album. I'm also quite fond of A Night At The Opera.


If you have better solution, just tell me !

And for a final little nugget of font goodness,

Zach Johnson is at it again, this time giving us a fun Friday treat with CSS text shadow, all via:

  1. document.getElementById('text-shadow-box').onmousemove = function(e) {
  2. var xm = e.clientX - 300;
  3. var ym = e.clientY - 175;
  4. var d = Math.sqrt(xm*xm + ym*ym);
  5. text.style.textShadow = -xm + 'px ' + -ym + 'px ' + (d / 5 + 10) + 'px black';
  6. xm = e.clientX - 600;
  7. ym = e.clientY - 450;
  8. spot.style.backgroundPosition = xm + 'px ' + ym + 'px';
  9. }

If you have better solution, just tell me !

Multiple font weights via CSS 3 and more font fun

The way @font-face works is that whatever font attributes you specify for a @font-face rule, they don’t determine how the font looks but rather when it’s gonna get used. For example if you have the following two rules.



  1. @font-face {
  2. font-family: newfont;
  3. src: local(Arial);
  4. font-weight: 200;
  5. }
  6. @font-face {
  7. font-family: newfont;
  8. src: local(Calibri);
  9. font-weight: 300;
  10. }

We posted on TypeKit recently, and we have another playa Kernest in the "fix friggin type on the Web" game.

And for a final little nugget of font goodness,

Typekit looks to include jQuery, loads CSS with base64-encoded data:font/otf URLs
for @font-face. "Safer" than a plain open .TTF, I suppose.

If you have better solution, just tell me !