search
HomeWeb Front-endH5 TutorialDetailed introduction of Html5 new tag datalist to realize dynamic matching of input box and background database data

HTML5Add tag datalist to realize that when inputting the first letter of Chinese/Pinyin, it will automatically enter the database fuzzy query, and Return the corresponding results and generate the datalist. Because when the input content in the input box changes, the datalist will automatically trigger the drop-down box. The solution is very good. I will share the example code with you through this article. Friends who need it can refer to it

A recent project involves a small function. When customers choose suppliers, due to the large number of suppliers (about 3000), it is obviously unrealistic to directly generate a drop-down box, so As for changing the solution, I plan to use the new tag datalist in HTML5 to automatically enter the database fuzzy query when entering the first letter of Chinese/Pinyin, and return the corresponding results to generate a datalist. When the input content in the input box changes, datalist will automatically trigger the drop-down box, so it is more convenient to use than select. The front-end code is as follows:

Html Code:

<!DOCTYPE html>  
<html lang="en">  
  <head id="head">  
    <title>库存下拉框测试</title>  
    <meta charset="utf-8">  
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <meta name="description" content="">  
    <meta name="author" content="">  
    <script src="../../Common/content/jquery-1.7.2.min.js"type="text/javascript"></script>  
    <script src="../../Common/pages/include.js" class="include" type="text/javascript"></script>  
    <script src="../../Common/js/AjaxJson.js"  type="text/javascript"></script>  
    <script src="../../Common/js/Setting.js"  type="text/javascript"></script>  
    <script src="../../Common/js/Paging.js"  type="text/javascript"></script>  
    <script src="../../Js/warehouseManage/testyy.js" type="text/javascript"></script>   
  </head>  
  <body class="">  
    <!--<![endif]-->  
    <p class="navbar"></p>  
    <p class="sidebar-nav"></p>  
    <p class="content">  
        <p class="header"><h1 id="下拉框测试">下拉框测试</h1></p>  
        <p class="container-fluid">  
            <p class="row-fluid">  
                <!-- --------------------------多条件查询--------------------------------------------- -->  
                <p class="well" id="searchDemo">  
                <p>测试数据(默认均为d00001):<br>    昆山市大陆配件有限公司     ksdlpjyxgs <br>  
                            亿真企业有限公司                        yzqyyxgs        <br>  
                            泰州市安誊轴皮厂(集团厂)   tzsatzpc(jtc)  
                </p>    
                </p>  
                    按 供应商名动态匹配(中文或者拼音均可):  
                    <input list="bro"  id="name"   oninput="this.value=this.value.replace(/^ +| +$/g,&#39;&#39;);search(&#39;name&#39;,&#39;bro&#39;,&#39;name&#39;)"  >  
                    <datalist  id="bro"></datalist>   
            </p>  
        </p>  
    </p>   
    </body>     
                <!-- -----------------------footer-------------------------- -->  
                <footer  class="foot"></footer>  
</html>

JavaScript Code:


var listobj=null;            //datalist对象  
var requestItem=null;        //后台返回的json数据中所需的key值  
var inputContent=null;       //input标签对象  
/**search()说明: 
 * inputID:     input标签的ID 
 * datalistID:  datalist标签的ID 
 * itemName:    后台返回的json数据中所需的key值(仅需表格中中文字段的属性名) 
 * */  
function search(inputID,datalistID,itemName)  
{  
    inputContent=document.getElementById(inputID);  
    var datalist=document.getElementById(datalistID);  
    //防止在无输入内容的情况下产生遗留下拉选项  
    if(inputContent.value.length==0||inputContent.value==" ")  
    {     
        var sub=datalist.childNodes;  
        if(sub.length>0)  
        {  
            for (var i =sub.length-1; i>=0 ; i--)   
            {  
                datalist.removeChild(sub[i]);         
            }  
        }  
        listobj=null;             
        requestItem=null;          
        inputContent.value=null;  
        return false;  
    }  
    //全局变量赋值  
    listobj=datalist;  
    requestItem=itemName;  
    var data="";  
    var url="";   
    if(/^[a-zA-Z]*$/.test(inputContent.value))  
    {  
        //检测出是拼音首字母  
        data="type=searchWords¶m="+inputContent.value;      //注意:data-----------需要自定义  
        url=baseurl + "/servlet/ListDemo";                      //注意:url-----------需要自定义  
        sendRequest("post",url,data,getResult);  
    }  
    else if (/^[\u4e00-\u9fa5]*$/.test(inputContent.value))  
    {  
        //检测出是中文  
        data="type=searchChinese¶m="+inputContent.value;    //注意:data-----------需要自定义  
        url=baseurl + "/servlet/ListDemo";                      //注意:url-----------需要自定义  
        sendRequest("post",url,data,getResult);  
    }  
}  
//填写仓库下拉框  
function getResult(result)   
{  
    var data=result;  
    var JData=eval("(" + data + ")");  
    var maxlength=10;              //注释:maxlength保证过多查询结果下只显示10条  
    if(JData.length<=10)  
    {    
        maxlength=JData.length;            
    }  
    var sub=listobj.childNodes;  
    for (var i =sub.length-1; i>=0 ; i--)   
    {  
        listobj.removeChild(sub[i]);    //清空datalist所有的下拉选项   
    }  
    if(JData.length==0)  //没有查询结果  
    {  
        alert("没有符合条件的结果,请重输");  
        inputContent.value="";    //清空input输入框的值  
        return false;  
    }  
    for (var i=0;i<maxlength;i++)   
    {  
         var obj=document.createElement("option");  
         var indexobj=JData[i];  
        if(/^[a-zA-Z]*$/.test(inputContent.value))  
        {   
             obj.value=indexobj[requestItem];  
             obj.innerHTML=inputContent.value;  
        }  
        if (/^[\u4e00-\u9fa5]*$/.test(inputContent.value))  
        {  
             obj.value=indexobj[requestItem];  
        }   
         listobj.appendChild(obj);       
    }  
    var suffix=document.createElement("option");  
    suffix.value=" ";  
    suffix.innerHTML="输入更多有关"+inputContent.value+"的信息";  
    listobj.appendChild(suffix);  
    return false;  
}

The above is the detailed content of Detailed introduction of Html5 new tag datalist to realize dynamic matching of input box and background database data. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools