코딩 공부/JS
자동완성 검색어 추천
hg_96
2022. 1. 19. 11:04
<!DOCTYPE html>
<html>
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#autoMaker{
padding : 3px;
position: absolute; width: 150px;
height: auto; background: white;
margin-top: 3px; cursor:pointer;
}
#autoMaker > div{
border : 1px solid #e6e6e6;
margin-top : 3px;
}
#autoMaker > div:hover{
background : gainsboro;
}
</style>
</head>
<body>
<!-- <input type="text" id='insert_target' readonly style='background: #cacaca'> -->
<input type="text" id='search_area'>
<div id='autoMaker'></div>
</body>
</html>
<script>
var ref = [
{key:1, name:'데이터1'},
{key:2, name:'데이터2'},
{key:3, name:'자바스크립트'},
{key:4, name:'Json'},
];
var isComplete = false; //autoMaker 자식이 선택 되었는지 여부
$('#search_area').keyup(function(){
var txt = $(this).val();
if(txt != ''){ //빈줄이 들어오면
$('#autoMaker').children().remove();
ref.forEach(function(arg){
if(arg.name.indexOf(txt) > -1 ){
$('#autoMaker').append(
$('<div>').text(arg.name).attr({'key':arg.key})
);
}
});
$('#autoMaker').children().each(function(){
$(this).click(function(){
$('#search_area').val($(this).text());
$('#insert_target').val("key : "+$(this).attr('key')+ ", data : " + $(this).text());
$('#autoMaker').children().remove();
isComplete = true;
});
});
} else {
$('#autoMaker').children().remove();
}
});
$('#search_area').keydown(function(event){
if(isComplete) { //autoMaker 자식이 선택 되었으면 초기화
$('#insert_target').val('')
}
})
</script>