JQuery에서 Select Box 제어 하기

munilive
munilive

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

munilive

munilive

Backend Application Developer

Share

Comments

Related Posts

JQuery : 클래스 이름만으로 페이지 전체에 롤오버 이미지 쉽게 적용하기

JQuery : 클래스 이름만으로 페이지 전체에 롤오버 이미지 쉽게 적용하기

마우스 오버 시 변경될 이미지를 쌍으로 만들어 사용할 경우 지정된 class만으로 롤오버 이미지를 자동 적용하는 스크립트에 대한 코드입니다.

munilive munilive ·
datepicker 시작일과 종료일 설정 시 사용하기 좋은 팁

datepicker 시작일과 종료일 설정 시 사용하기 좋은 팁

jQuery UI Datepicker를 이용하여 시작/종료일 설정 시 시작일은 종료일 이후 날짜를, 종료일은 시작일 이전날짜를 선택하지 못하게 하는 방법에 대한 설명 글이다.

munilive munilive ·
자바스크립트로 주간(일~토) 셀렉트 박스 만들기

자바스크립트로 주간(일~토) 셀렉트 박스 만들기

일요일~토요일 기간의 HTML SelectBox를 만들어주는 Javascript 예제 코드에 대하 글이다.

munilive munilive ·