Martin`s Work

[Jquery] select 태그 관련 기능 본문

Javascript/Jquery

[Jquery] select 태그 관련 기능

Martin`s Work 2017. 3. 10. 09:56

Select태그 관련한 기능


jquery에서 select태그에 기능을 넣기 위해 Selctor의 Dom을 가져오기 위한 몇가지 방법이 있다. 실제 이러한 방법을 쓰는 경우를 써야하는 경우는 여러가지 이유가 있겠지만, 그 중 하나로는 디자인 Select박스를 써야하는 경우가 있다. 단순 css만 이용하는 경우(:checked 속성)는 하위 브라우저에서 호환성 문제가 되어 이러한 경우 스크립트로 처리해야한다는 상황을 가정하에 작업한다.


현재 선택된 option의 값 가져오기


아래와 같이 select의 자식들 option에게 value 값을 부여하지 않으면 선택1, 선택2, 선택3 등과 같은 option의 innerText를 가져오게 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectbox">
    <option>선택1</option>
    <option>선택2</option>
    <option>선택3</option>
</select>
 
<script>
    var selectBox = $("#selectbox");
    selectBox.on("change"function(){
        console.log($(this).find("option:selected").val()); //선택된 options의 텍스트를 뱉음
    })
</script>
 
cs


만약 value를 추가 하면 선택된 option의 value 값을 가져올 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectbox">
    <option value="opt1">선택1</option>
    <option value="opt2">선택2</option>
    <option value="opt3">선택3</option>
</select>
 
<script>
    var selectBox = $("#selectbox");
    selectBox.on("change"function(){
        console.log($(this).find("option:selected").val()); //선택된 options의 텍스트를 뱉음
    })
</script>
 
cs


물론 상황에 따라서는 value값을 사용한 후 안의 텍스트나 index 번호를 구해야 하는 경우도 있다. 그러한 경우는 아래와 같이 사용하면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="selectbox">
    <option value="opt1">선택1</option>
    <option value="opt2">선택2</option>
    <option value="opt3">선택3</option>
</select>
 
<script>
    var selectBox = $("#selectbox");
    selectBox.on("change"function(){
        console.log($(this).find("option:selected").text()); //option의 value 값이 있을 경우 선택된 텍스트를 구해야 하는 경우
        console.log($(this).find("option:selected").index());   //선택된 option의 index 번호를 구해야 하는 경우
    })
</script>
cs



디자인 된 Selectbox 의 요소와 select태그의 option의 매칭


// text 값으로 select 하기

$("#selectBox").val("Some oranges").attr("selected""selected");

 

// value 값으로 select 하기

$("#selectBox").val("2");

$("#selectBox > option[@value=지정값]").attr("selected", "true");


// 선택된 옵션의 value 구하기

alert($("#selectBox option:selected").val());

 

// 선택된 옵션 index 구하기

alert($("#selectBox option").index($("#selectBox option:selected")));

 

// SelecBox 아이템 갯수 구하기

alert($("#selectBox option").size());

 

// 선택된 옵션 앞의 아이템 갯수

alert($("#selectBox option:selected").prevAll().size());

 

// 선택된 옵션 후의 아이템 갯수

alert($("#selectBox option:selected").nextAll().size());

 

// 0번째 item 다음에 삽입

$("#selectBox option:eq(0)").after("<option value='4'>Some pears</option>");

 

// 3번째 item 전에 삽입

$("#selectBox option:eq(3)").before("<option value='5'>Some apricots</option>");

 

// select box 값이 변경될때 선택된 현재값

$("#selectBox").change(function() {

           alert($(this).val());

           alert($(this).children("option:selected").text());

})


// select box Name로 접근하여 선택된 값 읽기
$("select[name=셀렉트박스name]").val();

// 같은 방식으로 span과 같은 다른 태그도 접근 가능하다~
$("span[name=셀렉트박스name]").text();

// 선택된 값의 index를 불러오기
var index = $("#셀렉트박스ID option").index($("#셀렉트박스ID option:selected"));

// 셀렉트 박스에 option값 추가하기
$("#셀렉트박스ID").append("<option value='1'>1번</option>");

// 셀렉트 박스 option의 맨앞에 추가 할 경우
$("#셀렉트박스ID").prepend("<option value='0'>0번</option>");

// 셀렉트 박스의 html 전체를 변경할 경우
$("#셀렉트박스ID").html("<option value='1'>1차</option><option value='2'>2차</option>");

// 셀렉트 박스의 index별로 replace를 할 경우
// 해당 객체를 가져오게 되면, option이 다수가 되므로 배열 객체가 되어 eq에 index를 넣어 개별 개체를 선택할 수 있다.
$("#셀렉트박스ID option:eq(1)").replaceWith("<option value='1'>1차</option>");

// 직접 index 값을 주어 selected 속성 주기
$("#셀렉트ID option:eq(1)").attr("selected", "selected");

// text 값으로 selected 속성 주기
$("#셀렉트ID")val("1번").attr("selected", "selected");

// value 값으로 selected 속성 주기
$("#셀렉트ID").val("1");

// 해당 index item 삭제하기
$("#셀렉트ID option:eq(0)").remove();

// 첫번째, 마지막 item 삭제하기
$("#셀렉트ID option:first").remove();
$("#셀렉트ID option:last").remove();

// 선택된 옵션의 text, value 구하기
$("#셀렉트ID option:selected").text();
$("#셀렉트ID option:selected").val();

// 선택된 옵션 전까지의 item 갯수 구하기
$("#셀렉트ID option:selected").prevAll().size();

// 선택된 옵션 후의 item 갯수 구하기
$("#셀렉트ID option:selected").nextAll().size();

// 해당 index item 이후에 option item 추가 하기
$("#셀렉트ID option:eq(0)").after("<option value='3'>3번</option>");

// 해당 index item 전에 option item 추가하기
$("#셀렉트ID option:eq(3)").before("<option value='2'>2번</option>");


출처: http://oingbong.tistory.com/175 [Oing]

'Javascript > Jquery' 카테고리의 다른 글

[JQuery] 다중 attr 처리  (0) 2017.04.20
[Jquery] Object비교  (0) 2017.03.13
[Jquery] event.which  (0) 2017.03.02
Comments