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

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

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

년도와 월을 선택하면 해당 년/월에 포함 되어있는 주 시작일과 종료일을 셀렉트박스로 만들게 하는 함수 입니다. 아래 이미지와 같은 모습이며, 예제 보기를 통해서 구현된 페이지를…

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

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

웹 프로그래밍을 하다 보면 가끔 시작일과 종료일을 입력받는 프로그램을 제작하곤 한다. 사용자에게 날짜를 입력받아야 하는데 텍스트 박스만 떡하니 놔두면 사용자가 제대로 된 데이터를…

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

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

작업중에 얻은 소스를 변경한것. 기존에는 지정한 파일 확장자의 이미지 만을 사용했다면 변경한 것에는 이미지 파일에 상관 없이 클래스명이 일때 무조건 확장자 앞에 의 유무에…

munilive munilive ·