JQuery에서 Select Box 제어 하기

munilive
Written by munilive on (Updated: )

JQuery에서 Selectbox를 컨트롤하는 방법에는 여러 가지가 있는데 자주 사용하는 방법에 대하여 바로 복사해서 사용 할 수 있도록 정리한다.

  • 현재 선택되어진 Selectbox의 값 읽기

     // Get selected value
     $("#myselectbox option:selected").val();
     // Get selected text
     $("#myselectbox option:selected").text();
     // Get selected index
     $("#myselectbox option").index($("#myselectbox option:selected"));
    
  • Selectbox의 Selected 값 설정

     // Set the element at index 2 to be selected
     $("#myselect option:eq(2)").attr("selected", "selected");
     // Set the selected element by text
     $("#myselect").val("Text1").attr("selected", "selected");
     // Set the selected element by value
     $("#myselect").val("Value1");
    
  • Selectbox의 option 추가

     // Add option to the end of a select
     $("#myselectbox").append("<option value='value1'>text1</option>");
     // Add option to the start of a select
     $("#myselectbox").prepend("<option value='value1'>text1</option>");
     // Insert an item in after a particular position
     $("#myselect option:eq(0)").after("<option value='Value4'>Text4</option>");
     // Insert an item in before a particular position
     $("#myselect option:eq(3)").before("<option value='Value5'>Text5</option>");
    
  • Selectbox의 option 변경

     // Replace all the options with new options
     $("#myselect").html("<option value='value1'>New Text1</option>
     <option value='Value2'>New Text2</option>");
     // Replace items at a certain index
     $("#myselect option:eq(1)").replaceWith("<option value='Value2'>New Text2</option>");
    
  • Selectbox의 option 삭제

     // Remove an item at a particular index
     $("#myselect option:eq(0)").remove();
     // Remove first item
     $("#myselect option:first").remove();
     // Remove last item
     $("#myselect option:last").remove();
    

원글 출처: https://donghunl.tistory.com/47

Comments

comments powered by Disqus