jQuery動態搜索下拉框

一,需求

初始隱藏,單擊喚出下拉框,可以在輸入框內輸入內容,下拉框模糊查詢出對應的數據顯示,單機選中下拉框內容後隱藏,並回顯選中的內容到輸入框內。
二,代碼

input.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>解決問題no解決代碼問題</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<style>
.search{
    display: block;
    position: absolute;
    z-index: 5px;
    background-color: #ffffff;
    width: auto;
    height: auto;
    border: 1px solid #000;
    overflow: auto;
    max-height: 400px;
}
</style>
<body>
<script type="text/javascript" >
$(document).ready(function(){
    var dataSource = [
        {id:"1",name:"1"},
        {id:"2",name:"12"},
        {id:"3",name:"13"},
        {id:"4",name:"14"},
        {id:"5",name:"112"},
        {id:"6",name:"1234"},
        {id:"7",name:"2"}
    ];
    coverOption(dataSource);
    $("#selectSearch").keyup(function(){
        var val1 =$("#selectSearch").val();
        var newList = [];
        for(var i=0;i<dataSource.length;i++){
            if(dataSource[i].name.indexOf(val1)>-1){
                newList.push(dataSource[i]);
            }
        }
        coverOption(newList);
    });
    $("#selectCustom").hide();
    $("#selectSearch").click(function(){
        $("#selectCustom").show();
    });
    var width1 = $(".zidingyi").width();
    $("#selectCustom").css("margin-left",(width1+5)+'px');
});


function coverOption(list){
    $("#selectCustom").html('');
    var tmp =[];
    for(var i=0;i<list.length;i++){
     var str = '<div><input class="in" name="selectCustom" title="'+list[i].name+'" '+
               ' type="radio" value="'+list[i].id+'" />'+list[i].name+'</div>';
        tmp.push(str);
    }    
    $("#selectCustom").html(tmp);
    $(".in").click(function(){
        var selectSearchVal = $("#selectCustom input[name='selectCustom']:checked").attr("title");
        $("#selectSearch").val(selectSearchVal);
        $("#selectCustom").hide();
    })
}

</script>
<label class="zidingyi">檢索 :</label>
<input type="text" id ="selectSearch"/>
<form ation="#" > <div id="selectCustom" class="search"> </div> </form>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章