2014-07-08 3 views
2

select 요소에서 javascript 검색을 만들었습니다.검색 및 제거 된 요소 제거

옵션 태그는 아무 것도 숨기거나 표시 할 CSS를 얻지 못합니다.이 솔루션을 위해 필적 할 수없는 옵션을 제거하고 재설정 목록 버튼에 대한 제거 된 옵션의 백업을 만듭니다.

잘 작동하지만 문제가 있습니다.이 선택 목록에 대해 약 19000 가지 옵션이 있습니다. 검색이 정상적으로 작동하지만 재설정 버튼을 누르면 19000에서 9500 옵션 만 되돌아옵니다.

감사합니다. 여기

코드입니다 : 내가 Y에서 관찰 한

CodePen Demo

HTML

<h1>Search in select "option" tag</h1> 
<select multiple name="selectMenu" id="selectMenu" style="width:100px" size=10> 
<option value ="item 1">item 1</option> 
<option value ="item 2">item 2</option> 
<option value ="thing 3">thing 3</option> 
<option value ="item 4">item 4</option> 
<option value ="stuff 5">stuff 5</option> 
<option value ="stuff 6">stuff 6</option> 
<option value ="stuff 7">stuff 7</option> 
<option value ="item 8">item 8</option> 
</select> 

<p>Search within this list</p> 
<input type=text name="search" id="search" onkeypress="searchItems();"> 
<br> 
<input type=button value="Search" onclick="searchItems();"> 
<input type=button value="Reset List" onclick="resetList();"> 

자바 스크립트

var itemList = null; 
var itemListOriginal = new Array(); 
var backup = false; 

function searchItems() { 
    itemList = document.getElementById("selectMenu"); 
    var searchStrObj = document.getElementById("search"); 
    var itemDescription = ""; 

    // replace white space with wild card 
    var searchString = searchStrObj.value; 
    searchString = searchString.replace(" ", ".*"); 

    var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag 

    if (itemListOriginal.length < 1) 
     backup = true; 
    else 
     backup = false; 

    // loop through options and check for matches 
    for (i=itemList.options.length - 1; i >=0 ; i--) { 
     itemDescription = itemList.options.item(i).text; 

     if (backup) { 
      hash = new Array(); 
      hash['name'] = itemDescription; 
      hash['value'] = itemList.options.item(i).value; 
      itemListOriginal[i] = hash; 
     } 

     if (!itemDescription.match(re)) { 
      itemList.remove(i); 
     } 
    } 

    return false; 
} 

function resetList() { 
    //hack! remove all elements from list before repopulating 
    for (i=itemList.options.length - 1; i >=0 ; i--) { 
     itemList.remove(i); 
    } 

    for (i=0; i < itemListOriginal.length; i++) { 
     hash = itemListOriginal[i]; 
     //option = new Option(hash['name'], hash['value']); REMOVED 
     //itemList.options.add(option, i); REMOVED 
     itemList.options[i] = new Option(hash['name'], hash['value'], false, false); 
    } 

    document.getElementById("search").value = ""; 
} 
+0

다음 번부터 링크를 첨부하지 말고 코드를 여기에 포함하십시오. –

+0

죄송합니다. 긴 코드 였고 일부 코드가 숨어 있었기 때문에 여기에 추가하기가 어려웠습니다. –

+0

네, 제발! 나는 다른 것을 편집하고 있기 때문에 그것을 위해 추가했습니다. –

답변

1

DEMO


우리 코드 백업은 당신이 함수 searchitems()을 호출 할 때마다 변경됩니다.

이렇게해서 저장된 이전 값을 지우십시오.

그래서 나는 그 뒤에 이유 즉

It is working fine but I have a problem, 
I have about 19000 option for this select list. 
search works fine but when I hit reset button, 
only 9500 option from 19000 comes back. 

것으로 변경했습니다. 그래서 코드를 수정하고 전역 변수 backupList을 추가했습니다. 원치 않는 요소가 제거되면 이전 요소가 내 코드에서 삭제되지 않고 대신 새로운 제거 된 요소가 += 약식 연산자를 사용하여 이전에 제거 된 요소에 추가됩니다.

도 않고 동적으로 options을 만들고 .add 또는 .append 또는 당신이 코드에서 볼 수 있듯이 단순화를 위해 .innerHTML을 사용하고 유사한 javascript 방법을 사용하여. 유일한 문제는 reset 요소를 클릭 한 후 첫 번째 경우와 같이 정렬되지 않으므로 정렬하기가 쉽습니다. 정렬에 대해서는 sort select menu alphabetically?을 참조하십시오.

var itemList = null; 
var itemListOriginal = new Array(); 
var backup = false; 
var backupList =""; // To store removed elements 

function searchItems() { 
itemList = document.getElementById("selectMenu"); 
var searchStrObj = document.getElementById("search"); 
var itemDescription = ""; 
var searchString = searchStrObj.value; 
searchString = searchString.replace(" ", ".*"); 
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag 
for (i=itemList.options.length - 1; i >=0 ; i--) { 
     itemDescription = itemList.options.item(i).text; 
     var hash = new Array(); 
     hash['name'] = itemDescription; 
     hash['value'] = itemList.options.item(i).value; 
     itemListOriginal[i] = hash; 
     if (!itemDescription.match(re)) { 
      itemList.remove(i); //Remove Unwanted Elements 
      backupList+="<option value='"+ hash['value']+"'>"+itemDescription+"</option>"; 
     /* append new unwanted elements with previous, 
      initially it is blank "". 
      This is Important 
     */ 
     } 
} 
return false; 
} 

function resetList() { 
var itemList = document.getElementById("selectMenu"); 
itemList.innerHTML+=backupList; /* Add removed elements to list. 
alternate to .append,.add or similar function*/ 
backupList=""; // Make Backup Empty! 
document.getElementById("search").value = ""; 
} 

희망 하시겠습니까? 환호 :)!

+0

와우 남자, 당신은 최고입니다, 완벽하게 작동합니다. 고마워. –

+0

그다지 :). 내가 너를 도울 수있어서 기뻐. 그리고 네 코딩 스타일은 초기에 나 자신을 생각 나게한다. +1 그런 질문에 대한 질문. –

+1

좋은 세부 사항을 가진 중대한 응답, 감사 다시. –