2012-07-18 4 views
0

확인란과 드롭 다운 목록이 있습니다. 확인란을 선택하면 드롭 다운 목록에 요소를 동적으로 추가 할 수있었습니다.HTML 드롭 다운 목록에서 항목을 제거 확인란의 선택 취소 이벤트

특정 체크 박스의 선택을 취소하면 어떻게 해당 항목을 드롭 다운 목록에서 동적으로 제거 할 수 있습니까?

여기에 내 코드

당신이 원하는 옵션의 인덱스를 찾아 인덱스를 제거해야합니다
//<input type="checkbox" name="docCkBox" value="${document.documentName}" onclick="handleChange(this)"/> 
// check box onclick event will call this function 
    function handleChange(cb) { 
     if (cb.checked) 
    { 

     // Create an Option object 
     var opt = document.createElement("option"); 

     // Add an Option object to Drop Down/List Box 
     document.getElementById("query_doc").options.add(opt); 

     // Assign text and value to Option object 
     opt.text = cb.value; 
     opt.value = cb.value; 


    } 

    else{ 


//I want to remove a particuler Item when I uncheck the check-box 
//by below method it will always remove the first element of the dropdown but not the corresponding element 

var opt = document.createElement("option"); 
opt.text = cb.value; 
opt.value = cb.value; 
document.getElementById("query_doc").remove(opt); 

} 


    } 

답변

1

이미 선택 태그에있는 옵션에 액세스해야하며 새 태그를 만들지 않아야합니다. 모든 옵션을 가져 와서 각 확인란을 선택하여 확인란의 값이 있는지 확인하면됩니다. 코드는 else 블록 안에 다음과 같이 표시됩니다.

var opts = document.getElementById("query_doc").getElementsByTagName('option'); 
for(var i = 0; i < opts.length; i++){ 
    if(opts[i].value == cb.value){ 
     opts[i].parentNode.removeChild(opts[i]); 
    } 
} 

코드를 테스트하지는 않았지만 일반적인 생각은 있습니다.

관련 문제