web Learning Notes 13 - Mobile Search Box Tips

Keywords: Javascript JSON JQuery github

Recently, the project has been updated iteratively, there is nothing new to do, so take out a small search module to share, the function is to input keywords can come out of the association of related words, delete some words can incidentally save a paragraph of association, from the appearance, the effect is still good, here to share for you, you can see.

The rendering is as follows, where is the github link search_demo

Following the old rules, I'm going to write the process directly.

Step 1: Create files

Create corresponding html, js, css files and introduce jquery.

Step 2: Introduce files, set meta, write html and style

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <!--General Media Query-->
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1, maximum-scale=1" />
<link rel="stylesheet" href="search.css">
<title>search</title>
</head>
<body>
<div class="search_nav">
    <input type="search" class="search_input searchProduct" placeholder="Find the goods you need">
    <div class="search_cancel">cancel</div>
</div>
<div class="search_find">
    <div class="search_history">
        History Search
    </div>
    <div class="search_find_line">
       <!--Search results and search history-->
    </div>
</div>

<script src="jquery.js"></script>
<script src="search.js" type="application/javascript"></script>
</body>
</html>


css:

*{
    margin: 0;
    padding: 0;
}
body{
    background-color: #f5f5f9;
}
.search_nav{
    width: 100%;
    height: 45px;
    position: fixed;
    top:0;
    left: 0;
    background-color: #20232b;
}
.search_input{
    float: left;
    width: 75%;
    height: 35px;
    margin-left: 30px;
    margin-top: 5px;
    font-size: 15px;
    text-indent: 30px;
    border: 1px solid black;
    border-radius: 40px;
    outline: none;
}
input::-webkit-search-cancel-button {display: none;}
.search_cancel{
    float: right;
    width: 15%;
    height: 100%;
    color:white;
    text-align: center;
    line-height: 45px;
}
.search_find{
    background:#fff;
    line-height:42px;
    margin-top: 45px;
}
.search_history{
    padding-left:10px;
    font-weight:700;
    font-size:16px
}
.search_find_title{
    display:block;
    position:relative;
    padding-left:15px;
    padding-right:10px;
    font-size:14px;
    color:#8a8a8a;
    width:100%;
    box-sizing:border-box
}
.search_find_title:after{
    content:'';
    position:absolute;
    top:0;
    left:15px;
    box-sizing:border-box;
    width:92%;
    height:1px;
    color:#ddd;
    border-bottom:1px solid #ddd;
    -webkit-transform-origin:0 0;
    transform-origin:0 0;
    -webkit-transform:scaleY(.4);
    transform:scaleY(.4)
}

Of course, the patterns and patterns in this area need to be adjusted according to their own projects in their actual projects. It does not need to be the same as I wrote, but the important part is the logic.

Step 3: Write js logic

In general, when we enter the search page, most of the historical searches, that is, search records, we need the rendering of the historical search first. I use the local Storage to store the historical searches here, and you can store or retrieve them according to your needs.

var history_search = [];//Storing historical search data

//Get historical search data, if not empty
if(localStorage.getItem("history_search")){
    history_search = JSON.parse(localStorage.getItem("history_search"));//Obtaining historical search data
}else{
    history_search = [];
}

Next, on the premise of obtaining the historical records, we need to render the historical records onto the page.



//Rendering Historical Records
function setpage(){
    var product_list = '';
    //Dynamically add elements to the page
    if(history_search.length != 0){
        $(".search_history").show();
        if(history_search.length >= 10){
            for(var i = 0; i < 10 ;i++){
                product_list = '<a class="search_find_title">'+history_search[i]+'</a>';
                $(".search_find_line").append(product_list);
            }
        }else{
            for(var i = 0; i < history_search.length;i++){
                product_list = '<a class="search_find_title">'+history_search[i]+'</a>';
                $(".search_find_line").append(product_list);
            }
        }
    }else{
        $(".search_history").hide();
    }
}
setpage();

What we need to note here is that the general historical records will not be too many. Generally, the first ten recent searches will be displayed. I intercepted them while rendering. In fact, I should make judgments when I saved them. When we exceeded 10 or specified the number of items, we only saved 10 or specified the number of items, and then we don't need to intercept intercept them when rendering.

Next, you need to process some requests and cache the searched prompt data when entering keywords.

var obj_arr = [];//Request result
var timeout = 0;
var keyName = '';//Search keywords
var ajaxCache = {};//Define the cache object (save the requested data)

Here I first put forward two other methods, one is to render the page, the other is to determine whether the string is empty, these two methods need to be invoked in the next logic.

//Rendering Page Method
function setListPage(obj,no){
    console.log(obj);
    console.log(no);
    ajaxCache = {};
    obj_arr = obj;
    $(".search_find_line").empty();
    if(no == 1){
        $(".search_history").hide();
    }else{
        $(".search_history").show();
    }

    var search_res = '';
    for(var i = 0; i < obj.length;i++){
        search_res = '<a class="search_find_title">'+obj[i]+'</a>';
        $(".search_find_line").append(search_res);
    }
}

//Determine whether the string is empty?
function isNull( str ){
    if ( str == "" ) return true;
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
}

Here is the most important part.

//When the button is loosened, trigger the event
$('.searchProduct').keyup(function(evt){
//Get keywords
    keyName = $(this).val();
//Judging whether the keyword is empty
    if(isNull(keyName) == false || keyName != ''){
        //If the input string is not empty, the network request search is displayed.
        clearTimeout(timeout);
        timeout = setTimeout(function(){
            if(!!ajaxCache[keyName]){
                //Display the automatic prompt box and fill in the contents of the related entries in the box
                setListPage(ajaxCache[keyName],1);
                ajaxCache = {};
            }else{
                var sendData = {
                    "keyName":keyName
                };

                $.ajax({
                    type: "POST",
                    url: url,//Our own interface is not open, you can use your own.
                    data:JSON.stringify(sendData),
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                        if(data){
                            if(data.data){
                                //Display the automatic prompt box and fill in the contents of the related entries in the box
                                ajaxCache[keyName]=[];
                                ajaxCache[keyName]=data.data;//Assigning values to cached objects
                                setListPage(data.data,1);
                            }
                        }
                    },
                    error: function (err) {
                        console.log(err);
                    }
                });
            }
        },200);
    }else{
        //If the input string is empty, the history search is displayed.
        ajaxCache = {};
        if(history_search.length == 0){
            //If the array is empty, the history search is not displayed
            $(".search_history").hide();
        }else{
            $(".search_history").show();
            setListPage(history_search,2)
        }
    }
//The trigger event occurs when the mobile phone press the search button in the lower right corner
   if (evt.keyCode == 13) {
        localStorage.setItem('search_keyName',keyName);
        var count = 0;
        //Judging whether the keyword of the current search exists in the Historical Search
        for(var j = 0; j < history_search.length;j++){
            if(keyName == history_search[j]){
                count += 1;
            }else{
                count += 0;
            }
        }
        //If not, add History Search
        if(count == 0){
            history_search.unshift(keyName);
        }
        //The lack of processing here is a problem of ranking historical searches.
        localStorage.setItem("history_search",JSON.stringify(history_search));
        window.location.href="";//Jump to pages like search results pages
    }

This is basically complete. There is no search result page added here. When prompt search appears, it should be in Add click events to jump to search results pages and so on, which can be handled according to their own needs.

Posted by cueball2000uk on Wed, 15 May 2019 08:07:17 -0700