Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 드롭다운 목록에서 옵션을 제거하는 방법

드롭다운 목록(select 요소)에서 옵션을 제거하려면 JavaScript의 remove() 메서드를 사용하면 됩니다. 이 메서드는 인덱스 값을 인자로 받아 해당 위치에 있는 옵션을 목록에서 삭제합니다.

아래 예제 코드를 실행하면 드롭다운 목록에서 옵션을 제거하는 방법을 직접 확인할 수 있습니다.

예제

<!DOCTYPE html>
<html>
   <body>
      <form id = "myForm">
         <select id = "selectNow">
            <option>One</option>
            <option>Two</option>
            <option>Three</option>
         </select>
         <input type = "button" onclick = "remove()" value = "Click to Remove">
      </form>
      <p>Select and click the button to remove the selected option.</p>
      
      <script>
         function remove() {
            var x = document.getElementById("selectNow");
            x.remove(x.selectedIndex);
         }
      </script>
      
   </body>
</html>

코드 설명

  • document.getElementById("selectNow"): id가 'selectNow'인 select 요소를 가져옵니다.
  • x.selectedIndex: 현재 사용자가 선택한 옵션의 인덱스 번호를 반환합니다.
  • x.remove(x.selectedIndex): 선택된 인덱스에 해당하는 옵션을 드롭다운 목록에서 제거합니다.

이처럼 remove() 메서드와 selectedIndex 속성을 함께 사용하면, 사용자가 선택한 옵션을 클릭 한 번으로 간단하게 삭제할 수 있습니다.