Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, May 9, 2011

Client-side HTML table pagination with JavaScript - NewInstance

Client-side HTML table pagination with JavaScript - NewInstance

Most of the times, you don't need to paginate on the client side: if you have an enough small set of records to be displayed, I would suggest you to choose a scrollable
.
Server-side web pagination is really needed when you have to display hundreds of records. You may fetch results from the DB using an offset and loading a single page for each HTTP request.
If your resultset is small it's possible to load it fully. Sometime I saw code loading the full resultset in session; and on each page-switch the browser refreshes displaying a different subset/page. There are many disadvantages of a server-side pagination like this:
  • You have to use the HTTP Session (and remember to clean up when it's nomore needed).
  • You have to reload the page on every page switch.
  • You cannot go forward and backward to check previous data without loosing the view on current resultset.
  • You have to write code for the server side actions handling all the page-switch work.
As I said before, everything would be solved using a table inside scrollable div but, in my current web application "GUI designers" like to persecute the users having them clicking and clicking even for few records. As in my case, I have an "editable table" (an html form) that's also paginated, in wich validation of each record depends on other records...
At least I wanted to avoid reloading the page on every page switch, and also avoid using HTTP Session when not strictly necessary. So I end up writing a JavaScript paginator object that handles the job of paginating any html table rendering also a simple pagination bar.
Here's a live sample:
# field
1
2
3



« Prev | 1 | 2 | 3 | 4 | Next »

That's all. If you want to download a demo (html+javascript files), you can click here: JavaScript Table Paginator Demo.
If you have a huge table, maybe it will be displayed fully before the javascript at the bottom will be executed. To avoid this, you can set the table as hidden by default using css style, and make it visibile using JavaScript after the pager.showPage() call.

Thursday, September 9, 2010

15款提高表格操作的jQuery插件


table表格由于它的浏览器兼容性和复杂的标签嵌套方式,可以算是添加样式最困难的对象之一了。大多数前端er都把网页中的table标签替 换为div,主要就是因为div要比table更容易添加CSS样式。但是我们在日常应用中仍然要用到table表格,其中最好的例子就是对照表。今天彬 Go将向大家推荐15个jQuery表格插件让你对数据表格进行显示、排序、筛选和操控。如jQuery表格排序插件、jQuery表格拖拽插件、jQuery树形表格插件、设置颜色、点击、替换等效果。

您还可以参考以下javascript相关资源:
《推荐9款很棒的网页绘制图表JavaScript框架脚本》
《了解jQuery技巧来提高你的代码》
《10种JavaScript特效实例让你的网站更吸引人》
《300+Jquery, CSS, MooTools 和 JS的导航菜单资源》

1.DataTables-强大的jQuery表格插件


datatables-jquery-插件
DataTables是提供了大量特性的强大jQuery表格插件。例如:你可以自动轻松筛选、Ajax预读取数据、分页、列排序、高亮排序列、扩展插件支持、使用CSS或jQuery UI ThemeRoller 定制主题和完整文档。

2.uiTableFilter-jQuery表格过滤插件


ui-table-filter-jquery-插件
uiTableFilter是一个用于表格行筛选的jQuery插件。插件作者提供了详细的例子来告诉大家如何将自己的表格和插件整合在一起并完成表格筛选。

3.Scrollable HTML Table-jQuery表格滚动插件


scrollable-html-table-jquery
Scrollable HTML Table jQuery插件可以让你的表格变得可以滚动控制。

4.Tablesorter-jQuery表格排序插件


tablesorter-jquery-插件
Tablesorter这个jQuery插件是用来将一个包含thead和tbody标签的标准HTML表格转变为无页面刷新的可排序表格。它不但支持多列排序,而且跨浏览器兼容并且能通过widget系统进行扩展。

5.Flexigrid-Web2.0 jQuery表格插件


flexigrid-jquery
Flexigrid 是一个轻量级的Web2.0 jQuery插件。它包含很多非常Cool的特性,如主题定制、分页、工具栏、搜索、排序、ajax读取数据源、调整列宽高尺寸等。

6.HeatColor-jQuery表格颜色插件


heatcolor-jquery
HeatColor可以让你根据元素的值来为元素设置颜色。 它的值的比对时根据预设的一个范围来进行比较,最后对他们自动进行颜色值的设置。

7.JQTreeTable-jQuery树形表格插件


jqtreetable-jquery
使用JQTreeTable插件你可以得到一个树形表格,如果用户的浏览器禁用了JavaScript,那么他们也能看到普通形式的表格,并不影响可访问性。

8.Ingrid-jQuery表格插件


ingrid-jquery-表格-插件
Ingrid是另一个数据表jQuery插件。它也有很多特性,比如列调整尺寸、排序、行列添加样式等。在作者网站提供了很棒的文档来告诉大家如何从头使用这个jQuery表格插件。

9.jQuery ColumnManager plugin


jquery-column-manager-jquery-表格插件
columnManager是可以控制任意表格列显示或隐藏的jQuery插件,而且它可以保存当前表格的状态至你下次访问。这个jQuery插件非常小巧轻量,仅3.6kb。

10.jQuery treeTable-jQuery树形表格插件


jquery-treetable-树形表格插件
jQuery treeTable是小型的JQTreeTable, 它也能让你的table显示成树形结构. 这个插件也可以在浏览器禁用JavaScript时保持文档整洁并让原始table可以使用.

11.CSV2Table-CSV格式读取表格插件


csv2table-jQuery表格插件
CSV2Table 可以读取CSV文件,它从CSV文件中读取内容并创建成table表格.

12.Table Pagination-jQuery表格分页插件


table-pagination-jQuery表格插件
这个jQuery表格分页插件可以在表格下面创建分页元素,你还可以通过各种设置来定制分页。

13.jQuery TableRowCheckboxToggle


jquery-table-插件
这个jQuery表格插件可以让你再点击表格行的时候改变多选框状态并修改该行CSS样式。

14.Table Drag and Drop jQuery plugin-jQuery表格拖拽插件


这个简单的jQuery插件可以让用户使用拖拽行的方式重新排列表格各行,任意单独行可以设置为不可拖拽和/或不可放置。

15.uiTableEdit


uiTableEdit是由Greg Weber制作的很酷的jQuery表格编辑插件,它允许用户编辑表格内容。



英文原文:15 Great jQuery Plugins For Better Table Manipulation


翻译原文:15款提高表格操作的jQuery插件(彬Go)

Monday, August 23, 2010

JavaScript验证函数大全

附加:js验证radio是否选择

<script language="javascript">
function checkform(obj)
{
for(i=0;i<obj.oo.length;i++)
          if(obj.oo[i].checked==true) return true;

alert("请选择")
return false;       

}
</script>
<form id="form1" name="form1" method="post" action=""    onsubmit="return checkform(this)">
    <input type="radio" name="oo" value="radiobutton" />
    <input type="radio" name="oo" value="radiobutton" />
    <input type="submit" name="Submit" value="提交" />
</form>

1. 长度限制
<script>
function test()
{
if(document.a.b.value.length>50)
{
alert("不能超过50个字符!");
document.a.b.focus();
return false;
}
}
</script>
<form name=a onsubmit="return test()">
<textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea>
<input type="submit" name="Submit" value="check">
</form>

2. 只能是汉字
<input onkeyup="value="/oblog/value.replace(/[^\u4E00-\u9FA5]/g,'')">

3." 只能是英文
<script language=javascript>
function onlyEng()
{
if(!(event.keyCode>=65&&event.keyCode<=90))
event.returnvalue=false;
}
</script>

<input onkeydown="onlyEng();">

4. 只能是数字
<script language=javascript>
function onlyNum()
{
if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
//考虑小键盘上的数字键
event.returnvalue=false;
}
</script>

<input onkeydown="onlyNum();">

5. 只能是英文字符和数字
<input onkeyup="value="/oblog/value.replace(/[\W]/g,"'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">

6. 验证油箱格式
<SCRIPT LANGUAGE=javascript RUNAT=Server>
function isEmail(strEmail) {
if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
return true;
else
alert("oh");
}
</SCRIPT>
<input type=text onblur=isEmail(this.value)>

7. 屏蔽关键字(这里屏蔽***和****)
<script language="javascript1.2">
function test() {
if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ("****") == 0)){
alert("123");
a.b.focus();
return false;}
}
</script>
<form name=a onsubmit="return test()">
<input type=text name=b>
<input type="submit" name="Submit" value="check">
</form>

8. 两次输入密码是否相同
<FORM METHOD=POST ACTION="">
<input type="password" id="input1">
<input type="password" id="input2">
<input type="button" value="test" onclick="check()">
</FORM>
<script>
function check()
{
with(document.all){
if(input1.value!=input2.value)
{
alert("false")
input1.value = "";
input2.value = "";
}
else document.forms[0].submit();
}
}
</script>

屏蔽右键 很酷
oncontextmenu="return false" ondragstart="return false" onselectstart="return false"
加在body中


二

2.1      表单项不能为空

<script      language="javascript">
<!--
function      CheckForm()
{ 
if      (document.form.name.value.length      ==      0)      { 
alert("请输入您姓名!");
document.form.name.focus();
return      false;
}
return      true;
}
-->
</script>

2.2      比较两个表单项的值是否相同

<script      language="javascript">
<!--
function      CheckForm()
if      (document.form.PWD.value      !=      document.form.PWD_Again.value)      { 
alert("您两次输入的密码不一样!请重新输入.");
document.ADDUser.PWD.focus();
return      false;
}
return      true;
}
-->
</script>

2.3      表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等

<script      language="javascript">
<!--
function      isNumber(String)
{ 
var      Letters      =      "1234567890-";      //可以自己增加可输入值
var      i;
var      c;
if(String.charAt(      0      )=='-')
return      false;
if(      String.charAt(      String.length      -      1      )      ==      '-'      )
return      false;
for(      i      =      0;      i      <      String.length;      i      ++      )
{ 
c      =      String.charAt(      i      );
if      (Letters.indexOf(      c      )      <      0)
return      false;
}
return      true;
}
function      CheckForm()
{ 
if(!      isNumber(document.form.TEL.value))      { 
alert("您的电话号码不合法!");
document.form.TEL.focus();
return      false;
}
return      true;
}
-->
</script>


2.4      表单项输入数值/长度限定

<script      language="javascript">
<!--
function      CheckForm() 
{ 
if      (document.form.count.value      >      100      ||      document.form.count.value      <      1)
{ 
alert("输入数值不能小于零大于100!");
document.form.count.focus();
return      false;
}
if      (document.form.MESSAGE.value.length<10)
{ 
alert("输入文字小于10!");
document.form.MESSAGE.focus();
return      false;
}
return      true;
}
//-->
</script>

2.5      中文/英文/数字/邮件地址合法性判断

<SCRIPT      LANGUAGE="javascript">
<!--

function      isEnglish(name)      //英文值检测
{ 
if(name.length      ==      0)
return      false;
for(i      =      0;      i      <      name.length;      i++)      { 
if(name.charCodeAt(i)      >      128)
return      false;
}
return      true;
}

function      isChinese(name)      //中文值检测
{ 
if(name.length      ==      0)
return      false;
for(i      =      0;      i      <      name.length;      i++)      { 
if(name.charCodeAt(i)      >      128)
return      true;
}
return      false;
}

function      isMail(name)      //      E-mail值检测
{ 
if(!      isEnglish(name))
return      false;
i      =      name.indexOf("      at      ");
j      =      name      dot      lastIndexOf("      at      ");
if(i      ==      -1)
return      false;
if(i      !=      j)
return      false;
if(i      ==      name      dot      length)
return      false;
return      true;
}

function      isNumber(name)      //数值检测
{ 
if(name.length      ==      0)
return      false;
for(i      =      0;      i      <      name.length;      i++)      { 
if(name.charAt(i)      <      "0"      ||      name.charAt(i)      >      "9")
return      false;
}
return      true;
}

function      CheckForm()
{ 
if(!      isMail(form.Email.value))      { 
alert("您的电子邮件不合法!");
form.Email.focus();
return      false;
}
if(!      isEnglish(form.name.value))      { 
alert("英文名不合法!");
form.name.focus();
return      false;
}
if(!      isChinese(form.cnname.value))      { 
alert("中文名不合法!");
form.cnname.focus();
return      false;
}
if(!      isNumber(form.PublicZipCode.value))      { 
alert("邮政编码不合法!");
form.PublicZipCode.focus();
return      false;
}
return      true;
}
//-->
</SCRIPT>

2.6      限定表单项不能输入的字符

<script      language="javascript">
<!--

function      contain(str,charset)//      字符串包含测试函数
{ 
var      i;
for(i=0;i<charset.length;i++)
if(str.indexOf(charset.charAt(i))>=0)
return      true;
return      false;
}

function      CheckForm()
{ 
if      ((contain(document.form.NAME.value,      "%\(\)><"))      ||      (contain(document.form.MESSAGE.value,      "%\(\)><")))
{ 
alert("输入了非法字符");
document.form.NAME.focus();
return      false;
}
return      true;
}
//-->
</script> 

1. 检查一段字符串是否全由数字组成      
---------------------------------------      
<script language="Javascript"><!--          
function checkNum(str){return str.match(/\D/)==null}          
alert(checkNum("1232142141"))          
alert(checkNum("123214214a1"))          
// --></script>        
     
2. 怎么判断是否是字符        
---------------------------------------      
if (/[^\x00-\xff]/g.test(s)) alert("含有汉字");         
else alert("全是字符");     
          
3. 怎么判断是否含有汉字       
---------------------------------------       
if (escape(str).indexOf("%u")!=-1) alert("含有汉字");        
else alert("全是字符");          
   
4. 邮箱格式验证   
---------------------------------------     
//函数名:chkemail    
//功能介绍:检查是否为Email Address    
//参数说明:要检查的字符串    
//返回值:0:不是 1:是    
function chkemail(a)    
{ var i=a.length;    
var temp = a.indexOf('@');    
var tempd = a.indexOf('.');    
if (temp > 1) {    
if ((i-temp) > 3){    
if ((i-tempd)>0){    
return 1;    
}    
   
}    
}    
return 0;    
}    
   
5. 数字格式验证   
---------------------------------------     
//函数名:fucCheckNUM    
//功能介绍:检查是否为数字    
//参数说明:要检查的数字    
//返回值:1为是数字,0为不是数字    
function fucCheckNUM(NUM)    
{    
var i,j,strTemp;    
strTemp="0123456789";    
if ( NUM.length== 0)    
return 0    
for (i=0;i<NUM.length;i++)    
{    
j=strTemp.indexOf(NUM.charAt(i));    
if (j==-1)    
{    
//说明有字符不是数字    
return 0;    
}    
}    
//说明是数字    
return 1;    
}    
   
6. 电话号码格式验证   
---------------------------------------     
//函数名:fucCheckTEL    
//功能介绍:检查是否为电话号码    
//参数说明:要检查的字符串    
//返回值:1为是合法,0为不合法    
function fucCheckTEL(TEL)    
{    
var i,j,strTemp;    
strTemp="0123456789-()# ";    
for (i=0;i<TEL.length;i++)    
{    
j=strTemp.indexOf(TEL.charAt(i));    
if (j==-1)    
{    
//说明有字符不合法    
return 0;    
}    
}    
//说明合法    
return 1;    
}   
  
7. 判断输入是否为中文的函数  
---------------------------------------     
function ischinese(s){  
var ret=true;  
for(var i=0;i<s.length;i++)  
ret=ret && (s.charCodeAt(i)>=10000);  
return ret;  
}   
  
8. 综合的判断用户输入的合法性的函数 
---------------------------------------     
<script language="javascript"> 
//限制输入字符的位数开始 
//m是用户输入,n是要限制的位数 
function issmall(m,n) 
{ 
if ((m<n) && (m>0)) 
      { 
      return(false); 
      } 
else 
{return(true);} 
} 
 
9. 判断密码是否输入一致 
---------------------------------------     
function issame(str1,str2) 
{ 
if (str1==str2) 
{return(true);} 
else 
{return(false);} 
} 
 
10. 判断用户名是否为数字字母下滑线
---------------------------------------     
function notchinese(str){
var reg=/[^A-Za-z0-9_]/g
        if (reg.test(str)){
        return (false);
        }else{
return(true);        }
}

11. form文本域的通用校验函数
---------------------------------------     
作用:检测所有必须非空的input文本,比如姓名,账号,邮件地址等等。
该校验现在只针对文本域,如果要针对form里面的其他域对象,可以改变判断条件。

使用方法:在要检测的文本域中加入title文字。文字是在提示信息,你要提示给用户的该字段的中文名。比如要检测用户名
html如下<input name="txt_1" title="姓名">,当然,最好用可视化工具比如dreamweaver什么的来编辑域。
如果要检测数字类型数据的话,再把域的id统一为sz.
javascript判断日期类型比较麻烦,所以就没有做日期类型校验的程序了.高手可以补充。

程序比较草,只是提供一个思路。抛砖引玉! :)
哦,对了,函数调用方法:< form      onsubmit="return dovalidate()">

function dovalidate()
{
fm=document.forms[0] //只检测一个form,如果是多个可以改变判断条件
        for(i=0;i<fm.length;i++)
        { 
        //检测判断条件,根据类型不同可以修改
        if(fm.tagName.toUpperCase()=="INPUT" &&fm.type.toUpperCase()=="TEXT" && (fm.title!=""))
   
             if(fm.value="/blog/="")//
             {
             str_warn1=fm.title+"不能为空!";
             alert(str_warn1);
            fm.focus();
             return false;        
             }
             if(fm.id.toUpperCase()=="SZ")//数字校验
             {
                     if(isNaN(fm.value))
                    { str_warn2=fm.title+"格式不对";
                    alert(str_warn2);
                    fm.focus();
                     return false;
                     }
            }
        }
        return true;
}


2 >表单提交验证类


2.1 表单项不能为空

<script language="javascript">
<!--
function CheckForm()
{
if (document.form.name.value.length == 0) {
alert("请输入您姓名!");
document.form.name.focus();
return false;
}
return true;
}
-->
</script>

2.2 比较两个表单项的值是否相同

<script language="javascript">
<!--
function CheckForm()
if (document.form.PWD.value != document.form.PWD_Again.value) {
alert("您两次输入的密码不一样!请重新输入.");
document.ADDUser.PWD.focus();
return false;
}
return true;
}
-->
</script>

2.3 表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等

<script language="javascript">
<!--
function isNumber(String)
{
var Letters = "1234567890-"; //可以自己增加可输入值
var i;
var c;
if(String.charAt( 0 )=='-')
return false;
if( String.charAt( String.length - 1 ) == '-' )
return false;
for( i = 0; i < String.length; i ++ )
{
c = String.charAt( i );
if (Letters.indexOf( c ) < 0)
return false;
}
return true;
}
function CheckForm()
{
if(! isNumber(document.form.TEL.value)) {
alert("您的电话号码不合法!");
document.form.TEL.focus();
return false;
}
return true;
}
-->
</script>


2.4 表单项输入数值/长度限定

<script language="javascript">
<!--
function CheckForm()
{
if (document.form.count.value > 100 || document.form.count.value < 1)
{
alert("输入数值不能小于零大于100!");
document.form.count.focus();
return false;
}
if (document.form.MESSAGE.value.length<10)
{
alert("输入文字小于10!");
document.form.MESSAGE.focus();
return false;
}
return true;
}
//-->
</script>

2.5 中文/英文/数字/邮件地址合法性判断

<SCRIPT LANGUAGE="javascript">
<!--

function isEnglish(name) //英文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return false;
}
return true;
}

function isChinese(name) //中文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return true;
}
return false;
}

function isMail(name) // E-mail值检测
{
if(! isEnglish(name))
return false;
i = name.indexOf(" at ");
j = name dot lastIndexOf(" at ");
if(i == -1)
return false;
if(i != j)
return false;
if(i == name dot length)
return false;
return true;
}

function isNumber(name) //数值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charAt(i) < "0" || name.charAt(i) > "9")
return false;
}
return true;
}

function CheckForm()
{
if(! isMail(form.Email.value)) {
alert("您的电子邮件不合法!");
form.Email.focus();
return false;
}
if(! isEnglish(form.name.value)) {
alert("英文名不合法!");
form.name.focus();
return false;
}
if(! isChinese(form.cnname.value)) {
alert("中文名不合法!");
form.cnname.focus();
return false;
}
if(! isNumber(form.PublicZipCode.value)) {
alert("邮政编码不合法!");
form.PublicZipCode.focus();
return false;
}
return true;
}
//-->
</SCRIPT>

2.6 限定表单项不能输入的字符

<script language="javascript">
<!--

function contain(str,charset)// 字符串包含测试函数
{
var i;
for(i=0;i<charset.length;i++)
if(str.indexOf(charset.charAt(i))>=0)
return true;
return false;
}

function CheckForm()
{
if ((contain(document.form.NAME.value, "%\(\)><")) || (contain(document.form.MESSAGE.value, "%\(\)><")))
{
alert("输入了非法字符");
document.form.NAME.focus();
return false;
}
return true;
}
//-->
</script>

Thursday, August 19, 2010

仿百度搜索输入框提示JS代码(PHP+MySql数据库版

转自:http://bbs.phpchina.com/thread-190409-1-1.html

HTML代码:
<div class="sidebarBlock" style="margin:0 auto; text-align:center;">
  <h3>仿百度搜索输入框提示JS代码(基于jquery.autocomplete.js插件)</h3>
  <form id="formkeyword" name="formkeyword" method="post" action="post.php">
    <div class="sidebarSearch">
          <input type="text" name="keyword" size="40" maxlength="255" value="" id="keyword" class="text"></input>
          <input type="submit" value="搜索" class="button"></input>
    </div>
  </form>
</div>
这是html的搜索框

JS代码:
<link href="css/jquery.autocomplete.css" type=text/css rel=stylesheet>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script language="javascript">
            $(document).ready(function() {
            $("#keyword").autocomplete("getajaxtag.php",
            {
                delay:10,
                minChars:1,
                matchSubset:1,
                matchContains:1,
                cacheLength:10,
                onItemSelect:selectItem,
                onFindValue:findValue,
                formatItem:formatItem,
                autoFill:false
            }
            );
            });
            function findValue(li) {
                if( li == null ) return alert("No match!");
                if( !!li.extra ) var sValue = li.extra[0];
                else var sValue = li.selectValue;
                }
            function selectItem(li) { findValue(li);}
            function formatItem(row) { return row[0];//return row[0] + " (id: " + row[1] + ")"//如果有其他参数调用row[1],对应输出格式Sparta|896
            }
            function lookupAjax(){
            var oSuggest = $("#keyword")[0].autocompleter;
            oSuggest.findValue();
            return false;
            }
</script>
Ajax获取后台数据库代码:
getajaxtag.php
<?php

include_once ('conn/conn.php');

$keyword = iconv ( 'utf-8', 'GBK', js_unescape ( $_GET ['q'] ) );
$sql = mysql_query ( "SELECT DISTINCT(tagname) FROM uchome_tag WHERE  tagname LIKE '%" . $keyword . "%'  LIMIT 0,10" );
while ( $value = mysql_fetch_array ( $sql ) ) {
    echo $keyword = iconv ( 'GBK', 'utf-8', $value ['tagname'] ) . "n";
}

function js_unescape($str) {
    $ret = '';
    $len = strlen ( $str );
    for($i = 0; $i < $len; $i ++) {
        if ($str [$i] == '%' && $str [$i + 1] == 'u') {
            $val = hexdec ( substr ( $str, $i + 2, 4 ) );
            if ($val < 0x7f)
                $ret .= chr ( $val );
            else if ($val < 0x800)
                $ret .= chr ( 0xc0 | ($val >> 6) ) . chr ( 0x80 | ($val & 0x3f) );
            else
                $ret .= chr ( 0xe0 | ($val >> 12) ) . chr ( 0x80 | (($val >> 6) & 0x3f) ) . chr ( 0x80 | ($val & 0x3f) );
            $i += 5;
        } else if ($str [$i] == '%') {
            $ret .= urldecode ( substr ( $str, $i, 3 ) );
            $i += 2;
        } else
            $ret .= $str [$i];
    }
    return $ret;
}
?>
需要的下载吧:下载地址

Wednesday, August 18, 2010

js input 鼠标点击清除提示内容,失去焦点还原默认内

js input 鼠标点击清除提示内容,失去焦点还原默认内容的方法
=======================================
function clearDefaultText (el,message)
{
var obj = el;
if(typeof(el) == "string")
obj = document.getElementByIdx_x(id);
if(obj.value == message)
{
obj.value = "";
}
obj.onblur = function()
{
if(obj.value == "")
{
   obj.value = message;
}
}
}

========================
实例
========================
<input type="text" id="searchKey" name="searchKey" value="请输入标题" onclick="clearDefaultText(this,'请输入标题')"/>

Tuesday, August 3, 2010

图片不存在的时候,显示一个默认图片

<img src="noexist.gif" http://www.lanrentuku.com/images/logo.jpg'" />
<p>查找更多代码,请访问:<a href="http://www.lanrentuku.com" target="_blank">懒人图库</a></p>

Friday, July 30, 2010

lhgdialog v3.1.3 弹出窗口插件

转自:http://www.cnblogs.com/lhgstudio/archive/2010/01/02/1637856.html





lhgdialog v3.1.3 弹出窗口插件体积更小,调用更简单,功能更强大。

下载地址:lhgdialog 弹出窗口插件v3.1.3

演示地址:lhgdialog 插件使用说明和演示

下载包中有使用说明文档,在使用插件前一定要先看看说明文档

lhgdialog v3.1.3 弹出窗口插件代码全部重构,整个插件只使用了一个lhgdialog.js核心文件,代码更加精减,规范。主库lhgcore.min.js也做了很多优 化,效率更高,插件的代码也做了很多优化,效率也更高,由于代码全部重写,所以也无法写出更新的东西,大家可以自已看_source目录里的源码。



3.1.3 更新内容

1. 修正参数为page时page的值每次打开窗口变化时内容页里取到的值不变的bug 注:如果想要page变化必须用第二种调用方式

2. 修正拖动改变大小时如果只单击不拖动程序出错的bug

3. 更改了所有类的名称,在所有的类名前加前缀lhgdig_,以防止和用户的类名冲突

4. 类库lhgcore.min.js有一点小的修正

----------------------------------------------------------

3.1.2 更新内容

1. 修正参数为html里窗口内容水平过多时撑开窗口的bug

2. 修正参数为page时在ie下有时单击窗口内容页时无权限的bug

3. 新增一款蓝色透明皮肤(此皮肤由网友Mr.Simple友情提供)

----------------------------------------------------------

3.1.1 更新内容

1. 窗口的html结构重新构造

2. 更新内容太多,自已看说明或源码吧(使用前一定要先看下使用说明)

----------------------------------------------------------

3.0.2 更新内容

1. 修正取页面滚动高度计算的BUG

2. 修正在IE下拖动时出现无权限的BUG

----------------------------------------------------------

3.0.1 更新内容

1. 修正IE8下内容页为iframe时高度的问题

2. 修正IE下当顶层页面为怪异模式时,内容页定位不准确的问题

----------------------------------------------------------

3.0.0 更新内容

更新内容太多,自已看说明或源码吧。

----------------------------------------------------------

2.3.7 更新内容

1. 主要是对使用遮罩时的每打开次窗口就创建一个遮罩层改为无论打开多少次都

    只创建一个遮罩层,这样可以提高效率,因为每创建一个遮罩就会增加很多内

    存的使用。

2. 主库文件lhgcore.min.js文件也升级为1.3.8,性能也有不少的提高。

----------------------------------------------------------

2.3.6 更新内容

1. 增加S.auto()函数,此函数是用来自动调整窗口大小。

2. 增加对link参数的控制,如果同域则不能使用link参数。

3. 修正了其它的一些小问题。

GreyBox弹出层框架基本使用

转自:http://www.okajax.com/a/200806/061S422008.html


GreyBox是www.open-open.com开发的一个遮罩层的组件,它运行以后可以产生不错的界面。类似于thinkbox,lightbox等。

下面我们先来看下效果吧



效果看上去还不错吧!这只是其中一个演示,还有很多。

那么现在就分享一下自己的经验:

1.进入GreyBox的网站(英文的):

http://orangoo.com/labs/GreyBox/

然后下载GreyBox

2.解压

先把这些包下的文件全部拷过来。



3.新建一个html页面,叫index.html

以下为代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>ddd</title>
<script type="text/javascript">
 var GB_ROOT_DIR = "./greybox/";
</script>
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJS_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<link href="greybox/gb_styles.css" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<h4>Example rendered:</h4>
<a href="static_files/salt.jpg" rel="gb_imageset[nice_pics]" title="Salt flats in Chile">Salt flats</a>
<a href="static_files/night_valley.jpg" rel="gb_imageset[nice_pics]" title="Night valley">Night valley</a>
</body>
</html>
那个var GB_ROOT_DIR="./greybox/";这个是指向你本机的greybox的相对目录。
接下来还有三个JavaScript文件和一个CSS,它是要用的要加进来。
第21行到22行,这两句是用来加入两张图片,以便切换,这样你就可以看到开始的那个Ajax的效果了。
不过使用这个的时候要注意第一行的代码不要忘记写。如果那样你就会发现窗体不会以符合你浏览器的大小来显示了。

<a href="static_files/salt.jpg" rel="gb_imageset[nice_pics]" title="Salt flats in Chile">Salt flats</a>href=""里面写的是你图片的路径,当然可以是网上的图片。rel是调用Js里面的方法(这个在它的官网上写的很详细 的)title是显示在框架上的标题,A标签里面的内容就不用说了,它指的是标题。
如果还想用其它的效果,可以点Documentation进去看看,而且还有很详细的例子和语法范例,很简单的,相信一看就会明白。

自动完成 Auto-Complete Field with jQuery

转:

  1. http://fromvega.com/wordpress/2007/05/05/auto-complete-field-with-jquery-json-php/
  2. http://zendgeek.blogspot.com/2009/07/zend-framework-and-dojo-auto-complete.html
  3. http://www.phpme.info/index.php/view_108_351.html

12.7.5  利用YUI库创建自动完成的文本输入框

http://book.51cto.com/art/201003/187298.htm

(the best one!)

Building AutoComplete Inputs with PHP, PEAR, Dojo and YUI

http://devzone.zend.com/article/4229


Fashion Statements


Coco Chanel, the famous French designer, once commented that fashion "is not something that exists in dresses only". In recent months, I've come to agree: ever since the big search engines added auto-suggest, hardly a week goes by without a client asking me to build similar autocomplete functionality into a Web form.


Fortunately, modern programming toolkits like Dojo provide ready-made widgets that have the necessary client-side functions for autocomplete. Add a little bit of server-side glue, in the form of a PHP script that talks to a database to generate valid suggestions, and enabling this functionality in a Web application now becomes a matter of hours, rather than days. In this article, I'll show you how to do this using three different libraries: PEAR HTML_QuickForm, YUI, and Dojo. Come on in, and find out more!

Back To Basics


Before we get started, it's important to state the assumptions this article makes. While most of the code in this tutorial involves the use of ready-made widgets, you'll still find it easier to navigate if you understand HTML, know the basics of JavaScript and DOM programming, and are familiar with retrieving and processing SQL result sets in PHP.


This article also assumes that you have an Apache/PHP/MySQL development environment already set up, and that you have downloaded and successfully installed the following packages:

  1. The Dojo/Dijit Toolkit, which is available from http://www.dojotoolkit.org/. This article uses Dojo v1.2.3.
  2. The Yahoo! User Interface (YUI) Library, which is available from http://developer.yahoo.com/yui/. This article uses YUI v2.6.0.
  3. The HTML_QuickForm package and all necessary dependencies, which is available from http://pear.php.net/package/HTML_QuickForm, and is currently maintained by Bertrand Mansion and Alexey Borzov. This article uses HTML_QuickForm v3.2.9

A quick word also about the MySQL database used in this article. The various examples that follow demonstrate autocomplete functionality in the context of a Web form that accepts book information, consisting of the book title and up to three author names. Based on the first few characters entered into the form, author names are dynamically suggested from a database table, which looks something like this:


 mysql> SELECT * FROM author LIMIT 0,10;
+----------+--------------------+
| AuthorID | AuthorName         |
+----------+--------------------+
|        1 | Stephen King       |
|        2 | Alfred Hitchcock   |
|        3 | Enid Blyton        |
|        4 | Ken Follett        |
|        5 | W. G. Moore        |
|        6 | Jeffrey Arthur     |
|        7 | John le Carre      |
|        8 | Scott Smith        |
|        9 | Alison Prince      |
|       10 | Arthur Conan Doyle |
+----------+--------------------+
10 rows in set (0.13 sec)

An SQL file containing example data for this table can be downloaded here.

Remote Control


Once all the pieces are in place, let's look at one approach to enabling autocomplete functionality: using YUI's AutoComplete widget. This widget, which is documented in detail at http://developer.yahoo.com/yui/autocomplete/, can be associated with any form input element and is a fully-skinnable, easy-to-configure component that can read suggestion data in a variety of formats.


Here's an example of a form that uses the AutoComplete widget:


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
  <link rel="stylesheet" type="text/css" href="/yui/build/fonts/fonts-min.css" />
  <link rel="stylesheet" type="text/css" href="/yui/build/autocomplete/assets/skins/sam/autocomplete.css" />
  <script type="text/javascript" src="/yui/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  <script type="text/javascript" src="/yui/build/connection/connection-min.js"></script>
  <script type="text/javascript" src="/yui/build/animation/animation-min.js"></script>  
  <script type="text/javascript" src="/yui/build/datasource/datasource-min.js"></script>
  <script type="text/javascript" src="/yui/build/autocomplete/autocomplete-min.js"></script>
  </head>
  <body class="yui-skin-sam">
    
    <h3>Add Title</h3>
    <form action="" method="post">
      Title:<br/>
      <input type="text" name="Title[TitleName]" style="width:200px"/>
      <p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][0]" type="text" name="Author[AuthorName][0]"/>
        <div id="ac0"></div>
      </div>
      <p/><br/><p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][1]" type="text" name="Author[AuthorName][1]"/>
        <div id="ac1"></div>
      </div>
      <p/><br/><p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][2]" type="text" name="Author[AuthorName][2]"/>
        <div id="ac2"></div>
      </div>
      <p/><br/><p/>
      <input type="submit" name="submit" value="Save" />
    </form>    
    
    <script type="text/javascript">                
      YAHOO.example.autocomplete = function() {
        var oConfigs = {
            prehighlightClassName: "yui-ac-prehighlight",
            queryDelay: 0,
            minQueryLength: 0,
            animVert: .01,
        }
        
        // instantiate remote data source
        // code based on example at
        // http://developer.yahoo.com/yui/examples/autocomplete/ac_basic_xhr.html
        var oDS = new YAHOO.util.XHRDataSource("http://localhost/get_authors.php");
        oDS.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
        oDS.responseSchema = {
           resultNode: 'author',
           fields: ['name']            
        };
        oDS.maxCacheEntries = 10;        
    
        // instantiate YUI autocomplete widgets
        var oAC0 = new YAHOO.widget.AutoComplete("Author[AuthorName][0]", "ac0", oDS, oConfigs);          
        var oAC1 = new YAHOO.widget.AutoComplete("Author[AuthorName][1]", "ac1", oDS, oConfigs);          
        var oAC2 = new YAHOO.widget.AutoComplete("Author[AuthorName][2]", "ac2", oDS, oConfigs);
        return {
            oDS: oDS,
            oAC0: oAC0,
            oAC1: oAC1,
            oAC2: oAC2
        };
      }();
     </script>
    
  </body>
</html>


As the code illustrates, this form contains three input fields, each of which is associated with an AutoComplete widget. As the user begins entering data into each of these fields, the AutoComplete widget will go to work generating suggestions that match the user's input. The source data for these suggestions is YUI's XHRDataSource widget, which is configured as below:


         // instantiate remote data source
        var oDS = new YAHOO.util.XHRDataSource("http://localhost/get_authors.php");
        oDS.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
        oDS.responseSchema = {
           resultNode: 'author',
           fields: ['name']            
        };


This configuration tells the XHRDataSource widget that it should automatically poll the PHP script at 'http://localhost/get_authors.php' for suggestions, and warns it that the PHP script will express these suggestions in XML. The configuration also specifies the XML node and attribute names that contain the suggestion text.


At the other end of the connection, here's what the 'get_authors.php' script looks like:


 <?php
// begin XML output
$xmlStr = <<<XML
<?xml version='1.0' standalone='yes'?>
<authors>
XML;

// open database connection
$mysqli = new mysqli("localhost", "user", "pass", "library");      
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

// retrieve author list matching input
// add to XML document
$q = $mysqli->real_escape_string($_GET['query']);
$sql = "SELECT AuthorName FROM author WHERE AuthorName LIKE '" . $q . "%' ORDER by AuthorName";
if ($result = $mysqli->query($sql)) {
  while ($row = $result->fetch_row()) {
    $xmlStr .= '<author name="' . $row[0] . '"></author>';
  }
  $result->close();
}

// clean up
// output XML document
$mysqli->close();
$xmlStr .= '</authors>';
header("Content-Type: text/xml");
echo $xmlStr;
?>


There's nothing particularly complicated about this script. It receives the string fragment entered by the user in $_GET['query'], formulates an SQL query to generate author names matching this fragment, and outputs an XML document containing these author names. Here's an example of the XML it generates in response to a query for 'ste':


 <?xml version='1.0' standalone='yes'?>
<authors>
  <author name="Stephen Fry"></author>
  <author name="Stephen King"></author>
  <author name="Stephen Mogridge"></author>
</authors>


At the other end of the connection, this XML is parsed and decoded by YUI's XHRDataSource widget and presented to the user. Here's an example of what the output looks like:

Going Local


One important point to note about the previous example, is that it continually "polls" the server to refine the suggestion list, as the user is typing. This might not be ideal in all situations - for example, when you're on a slow network link, or if your server is already heavily loaded and you don't want to unnecessarily burden it with additional work.


In these situations, you can populate the AutoComplete widget from a local data source - an inline JavaScript array - instead of from a remote URL. In this case, the array is dynamically generated using PHP when the page is rendered and used as the base for all autocomplete suggestions. The PHP code used to generate and populate the JavaScript array is similar to that used in the previous example. Here's the revised form:


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
  <link rel="stylesheet" type="text/css" href="/yui/build/fonts/fonts-min.css" />
  <link rel="stylesheet" type="text/css" href="/yui/build/autocomplete/assets/skins/sam/autocomplete.css" />
  <script type="text/javascript" src="/yui/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  <script type="text/javascript" src="/yui/build/animation/animation-min.js"></script>  
  <script type="text/javascript" src="/yui/build/datasource/datasource-min.js"></script>
  <script type="text/javascript" src="/yui/build/autocomplete/autocomplete-min.js"></script>
  </head>
  <body class="yui-skin-sam">
    
    <h3>Add Title</h3>
    <form action="" method="post">
      Title:<br/>
      <div style="width:200px">
        <input type="text" name="Title[TitleName]"/>
      </div>
      <p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][0]" type="text" name="Author[AuthorName][0]"/>
        <div id="ac0"></div>
      </div>
      <p/><br/><p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][1]" type="text" name="Author[AuthorName][1]"/>
        <div id="ac1"></div>
      </div>
      <p/><br/><p/>
      Author:<br/>
      <div style="width:200px">
        <input id="Author[AuthorName][2]" type="text" name="Author[AuthorName][2]"/>
        <div id="ac2"></div>
      </div>
      <p/><br/><p/>
      <input type="submit" name="submit" value="Save" />
    </form>    
    
    <?php
    // open database connection
    $mysqli = new mysqli("localhost", "user", "pass", "library");      
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
", mysqli_connect_error());
        exit();
    }
    // retrieve author list
    $query = "SELECT AuthorName FROM author ORDER by AuthorName";
    $authors = array();
    if ($result = $mysqli->query($query)) {
      while ($row = $result->fetch_row()) {
        $authors[] = $row[0];
      }
      $result->close();
    }
    // clean up
    $mysqli->close();
    ?>      
  
    <script type="text/javascript">                
      // set data
      arrayAuthors = [
        "<?php echo implode('","', $authors); ?>"
      ];      
      
      YAHOO.example.autocomplete = function() {
        var oConfigs = {
            prehighlightClassName: "yui-ac-prehighlight",
            queryDelay: 0,
            minQueryLength: 0,
            animVert: .01,
        }
        
        // instantiate local data source
        // code based on example at
        // http://developer.yahoo.com/yui/examples/autocomplete/ac_basic_array.html
        var oDS = new YAHOO.util.LocalDataSource(arrayAuthors);
    
        // instantiate YUI autocomplete widgets
        var oAC0 = new YAHOO.widget.AutoComplete("Author[AuthorName][0]", "ac0", oDS, oConfigs);          
        var oAC1 = new YAHOO.widget.AutoComplete("Author[AuthorName][1]", "ac1", oDS, oConfigs);          
        var oAC2 = new YAHOO.widget.AutoComplete("Author[AuthorName][2]", "ac2", oDS, oConfigs);
        
        return {
            oDS: oDS,
            oAC0: oAC0,
            oAC1: oAC1,
            oAC2: oAC2
        };
      }();
     </script>
    
  </body>
</html>


You'll notice also that in this version, the autocomplete suggestions appear quicker, because the widget is operating off a local array rather than a remote request. However, this method is only advisable when the data set is relatively small, as otherwise the inline JavaScript array might grow too large and consume an uncomfortably high amount of client memory.

Typing Tutor


An alternative to the previous example is to use HTML_QuickForm's 'autocomplete' element, which also uses a local data cache and is fairly straightforward to implement. Here's an example:


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head></head>
  <body>
    <h3>Add Title</h3>

    <?php
    // open database connection
    $mysqli = new mysqli("localhost", "user", "pass", "library");      
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
", mysqli_connect_error());
        exit();
    }
    // retrieve author list
    $query = "SELECT AuthorName FROM author ORDER by AuthorName";
    $authors = array();
    if ($result = $mysqli->query($query)) {
      while ($row = $result->fetch_row()) {
        $authors[] = $row[0];
      }
      $result->close();
    }
    // clean up
    $mysqli->close();
        
    // initialize HTML_QuickForm object
    require_once 'HTML/QuickForm.php';
    $form = new HTML_QuickForm();
    
    // add auto-complete input field
    $title = $form->addElement('text', 'Title[TitleName]', 'Title:');
    $ac0 = $form->addElement('autocomplete', 'Author[AuthorName][0]', 'Author:');
    $ac1 = $form->addElement('autocomplete', 'Author[AuthorName][1]', 'Author:');
    $ac2 = $form->addElement('autocomplete', 'Author[AuthorName][2]', 'Author:');
    
    // add auto-complete options
    $ac0->setOptions($authors);
    $ac1->setOptions($authors);
    $ac2->setOptions($authors);
    
    // add submit button
    $form->addElement('submit', null, 'Submit');
    
    // print submitted values
    // render and display the form
    if ($form->validate()) {
      $form->freeze();
    } else {
      $form->display();
    }
    ?>
  </body>
</html>


Here, an 'autocomplete' element is first added to the form with addElement(), and then its setOption() method is used to set the array of values that will be used for auto-completion. When the form is rendered, as the user types a name into the autocomplete field, the input entered will be matched against this array of values (on every key press) and matching values, if any, will be used to complete the user's input. Here's an illustration of what this looks like:



In this example, the array is generated by PHP from a MySQL result set, as in the earlier examples. The HTML_QuickForm package will use this array and automatically generate the JavaScript code needed to enable the autocompletion feature (look in the source code of the rendered page to see it).

Dijit-al Download


If you're a Dojo fan, then you'll be thrilled to hear that Dijit, the Dojo widget library, also comes with a ComboBox component that exposes autocomplete functionality. This ComboBox can be linked to an ItemFileReadStore, which provides suggestions using a JSON source (although other formats are also supported). Here's the code:


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <style type="text/css">
      @import "/dojo-release-1.2.3/dijit/themes/tundra/tundra.css";
      @import "/dojo-release-1.2.3/dojo/resources/dojo.css"
    </style>  
    <script type="text/javascript" src="/dojo-release-1.2.3/dojo/dojo.js" djConfig="parseOnLoad: true"></script>
    <script type="text/javascript">
     dojo.require("dojo.parser");
     dojo.require("dijit.form.ComboBox");
     dojo.require("dojo.data.ItemFileReadStore");
    </script>
  </head>
  <body>
    <!--
    code based on example at
    http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit/form-validation-specialized-input/auto-completer
    -->
    <h3>Add Title</h3>
    <form action="" method="post">
      <div dojoType="dojo.data.ItemFileReadStore" jsId="aStore" url="http://localhost/get_authors_json.php" />
      Title:<br/>
      <div class="tundra" style="width:200px">    
        <input type="text" dojoType="dijit.form.TextBox" name="Title[TitleName]" />
      </div>
      <p/>
      Author:<br/>
      <div class="tundra" style="width:200px;">
        <input name="Author[AuthorName][0]" dojoType="dijit.form.ComboBox" store="aStore" searchAttr="name" />          
      </div>
      <p/>
      Author:<br/>
      <div class="tundra" style="width:200px">
        <input name="Author[AuthorName][1]" dojoType="dijit.form.ComboBox" store="aStore" searchAttr="name" />          
      </div>
      <p/>
      Author:<br/>
      <div class="tundra" style="width:200px">
        <input name="Author[AuthorName][2]" dojoType="dijit.form.ComboBox" store="aStore" searchAttr="name" />          
      </div>
      <p/>
      <input type="submit" name="submit" value="Save" />
    </form>    
    
  </body>
</html>


Notice, in the listing above, that each ComboBox element has a 'store' attribute, which points to the Dojo ItemFileReadStore. This ItemFileReadStore looks for JSON data to be in a particular format, which is documented at http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/what-dojo-data/available-stores/dojo-data-item. It's quite easy to generate this JSON data using a server-side PHP script, which is exactly what the script at 'http://localhost/get_authors_json.php' does:


 <?php
// open database connection
$mysqli = new mysqli("localhost", "user", "pass", "library");      
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}
// retrieve author list matching input
// add to XML document
$sql = "SELECT AuthorName FROM author ORDER by AuthorName";
if ($result = $mysqli->query($sql)) {
  while ($row = $result->fetch_row()) {
    $authors[] = array('name' => $row[0]);
  }
  $result->close();
}

// clean up
// output JSON
$mysqli->close();
echo json_encode(array('identifier' => 'name', 'items' => $authors));
?>


Here's an example of the JSON output:


 {"identifier":"name",
"items":[
          {"name":"A. J. Quinnell"},
          {"name":"Agatha Christie"},
          ...
          {"name":"William McKay"},
          {"name":"William Rotsler"}
         ]

}


And here's what the final product looks like:



As these examples demonstrate, it's fairly easy to build an autocomplete input that uses a database for suggestions, by mixing a little PHP with ready-made widgets from toolkit such as Dojo or YUI. This article listed four possible ways in which this could be done...but there are many more! Play with it a little, discover your own...and don't forget to post a comment telling everyone about it!

JQuery 浮动导航栏实现代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JQuery 浮动导航栏</title>
<script type="text/javascript" src="http://img.jb51.net/jslib/jquery/jquery-1.3.2.min.js"></script>
<style type="text/css">

#floatMenu
{
padding-top: 5px;
background: url(http://img.jb51.net/images/quickmenu.gif) no-repeat;
border: 1px solid #dcdcdc;
position: absolute;
top: 250px;
left: 5px;
margin-left: 0px;
width: 86px;
}
#floatMenu ul
{
margin-left: 0px;
background-color:White;
list-style-type: none;
padding:10px

}
#floatMenu ul li a
{
display: block;
text-decoration: none;
color: #000;
}
#floatMenu ul li a:hover
{
color: #fff;
background-color: #ff8000;
}
#floatMenu ul.menu1 li a:hover
{
border-color: #09f;
}

</style>
</head>
<body>
<div id="floatMenu">
<ul class="menu1">
<li><a href="#" onclick="return false;">Home</a></li>
<li><a href="#" onclick="return false;">About Us</a></li>
<li><a href="#" onclick="return false;">Product</a></li>
<li><a href="#" onclick="return false;">Contact</a></li>
</ul>
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br
/><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br
/><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br
/><br />
<script type="text/javascript">
//<![CDATA[
var name = "#floatMenu";
var menuYloc = null;
$(document).ready(function() {
menuYloc = parseInt($(name).css("top").substring(0, $(name).css("top").indexOf("px")))
$(window).scroll(function() {
offset = menuYloc + $(document).scrollTop() + "px";
$(name).animate({ top: offset }, { duration: 500, queue: false });
});
});
//]]>
</script>
</body>
</html>

JS实例:文本输入框是不可编辑的,我想让它可以点一下

单个文本框


<html>
<head>
<script type="text/JavaScript" language="JavaScript">
function doclick(){
var docs = document.getElementByIdx_x('url');
docs.readOnly = false;
//alert("asdfasd");
}
</script>
</head>
<body>
<input type="text" id="url" name="T_montant" value="com" readOnly />
<input type="button" value="edit" onclick="doclick();">
</body>
</html>





多个文本框:
<html>
<head>
<script language="javascript">
function doclick(){
var docs = document.all("T_montant");
docs[0].readOnly = false;
docs[1].readOnly = false;}
</script>
</head>
<body>
<input type="text" id="url" name="T_montant" value="com" readOnly />
<input type="text" id="url" name="T_montant" value="sdsa" readOnly />
<input type="button" value="edit" onclick="javascript:doclick()">
</body>
</html>

JS实例:一个输入框一个按钮,点按钮时把文本框中的内

<html>
<head>
<script language="javascript">
function Open(){
  var url = document.getElementByIdx_x("url").value;
  window.open (url);
}
</script>
</head>
<body>
<input type="text" id="url" value=" http://baidu.com"/>
<input type="button" value="submit" onclick="Open()">
</body>
</html>  

JS实例:两个input 文本输入框 改变其中一个的值 另一

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language="JavaScript">
function keydown(){
  document.ff.input2.value=document.ff.input1.value;
}
</script>
</HEAD>

<BODY>
<form action="" name="ff" method="post">
  <input type="text" name="input1" onkeyup="keydown()"><br>
  <input type="text" name="input2">
</form>
</BODY>
</HTML>  

几种设置表单元素中文本输入框不可编辑的方法


本文转自:http://www.qljyzx.com:88/Article/homepage/asp/200611/713.html


作者:佚名


解决思路:
在文本框的内容只作于演示而不允许用户随意修改时 这样做就非常有必要。


具体步骤:
方法一:设置readonly属性为true。




Html代码
  1. <input type="text" value="readonly" readonly>   

 <input type="text" value="readonly" readonly>  

 

方法二:设置disabled属性为true。




Html代码
  1. <input type="text" value="disabled" disabled>   

 <input type="text" value="disabled" disabled>  

 

方法三:在对象focus时立刻让它blur,使它无法获得焦点。




Html代码
  1. <input type="text" value="onfocus=this.blur()" onfocus="this.blur()">   

 <input type="text" value="onfocus=this.blur()" onfocus="this.blur()">  
 

提示:readonly和disabled的区别在 于后者完全禁止与设置该属性的对象交互(表现为不可改写、不可提交等)。 readonly是可以提交的


特别提示
代码运行效果如图1.4.16所示。
图片
图1.4.16 禁止输入的文本框

特别说明



本例需要了解readonly和disabled属性的用法,两属性的区别见第三部分问题43。需要掌握的一个技巧是如何让对象得不到焦 点,主是要下面的事件或方法的应用:
onfocus当对象获得焦点时触发。
focus使对象得到焦点。
onblur在对象 失去输入焦点时触发。
blur模糊对象的内容以便使其看起来失去焦点。

javascript(表单元素--select下拉列表)制作二级联动

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" ontent="text/html; charset=gb2312" />
<title>表单元素(select下拉列表)制作二级联动菜单和网站导航</title>
<script language="javascript">
//下面函数是联动菜单的处理代码
function makeshi(x){
var form2=document.diqu.one.options.length;//这句解释同上
var diqul=new Array(form2)//新建一个数组,项数为第一个下拉列表的项数
for(i=0;i<form2;i++)//循环第一个下拉列表的项数那么多次
diqul[i]=new Array();//子循环
//下面是给每个循环赋值
diqul[0][0]=new Option("绵阳","绵阳");
diqul[0][1]=new Option("成都","成都");
diqul[0][2]=new Option("广元","广元");
diqul[1][0]=new Option("南京","南京");
diqul[1][1]=new Option("苏州","苏州");
diqul[1][2]=new Option("常州","常州");
diqul[2][0]=new Option("南宁","南宁");
diqul[2][1]=new Option("柳州","柳州");
diqul[2][2]=new Option("北海","北海");
diqul[3][0]=new Option("杭州","杭州");
diqul[3][1]=new Option("温州","温州");
diqul[3][2]=new Option("义乌","义乌");
var shi=document.diqu.shi;//方便引用
for(m=shi.options.length-1;m>0;m--)
//这个要看清楚,因为要重新填充下拉列表的话必须先清除里面原有的项,清除和增加当然是有区别的了,所以用递减
shi.options


­=null;//将该项设置为空,也就等于清除了
for(j=0;j<diqul[x].length;j++){//这个循环是填充下拉列表
shi.options[j]=new Option(diqul[x][j].text,diqul[x][j].value)
//注意上面这据,列表的当前项等于 新项(数组对象的x,j项的文本为文本,)
}
shi.options[0].selected=true;//设置被选中的初始值
}
</script>
</head>
<body>
<p>对于脚本来说,最复杂的表单元素对象就是select了,他是一个复合对象,包含OPTION对象数组的对象</p>
<p><strong>演示:地区二级无刷新联动菜单</strong>(其实这个例题也适用了关联数组,只是说被 关联的数组是在一级数组的内部,如果有不明白,就看下 <a href="http://www.cnblogs.com/thcjp/archive/2006/08/04/467761.html">http://www.cnblogs.com/thcjp/archive/2006/08/04/467761.html</a> 这篇,专门介绍数组的文字)</p>
<form id="form2" name="diqu" method="post" action="">
<select name="one" size="1" onchange="makeshi(options.selectedIndex)">
<option value="0">四川</option>
<option value="1">江苏</option>
<option value="2">广西</option>
<option value="3">浙江</option>
</select>
<select name="shi">
<option value="绵阳">绵阳</option>
<option value="成都">成都</option>
<option value="德阳">德阳</option>
<option value="广元">广元</option>
<option value="南充">南充</option>
</select>
</form>
</body>
</html>



转自: http://hi.baidu.com/oxolin/blog/item/a0c9a94a2057d72808f7ef8f.html