반응형
jQuery를 통해 select박스 제어를 알아보겠습니다.
/********** value **********/
$(선택자).val(); //value값 가져오기
$("#id").val(); //id로 접근하여 value가져오기
$("select[속성='속성명']").val(); //속성으로 접근하여 value가져오기
/********** text **********/
$(선택자 option:selected).text(); //text값 가져오기
$("#id option:selected").text();
$("select[속성='속성명'] option:selected").text();
text값은 가져올때 해당자식인 option의 선택된 개체를 가져와야합니다. option:selected
해당 옵션이 없으면 select 자식으로 들어간 option값 전부를 가져오게 됩니다.
change이벤트에 따른 val값 및 text값을 가져오는 예제
name속성이 location인 select박스의 값이 변경됨에 따른 선택값 처리를 알아보겠습니다.
HTML
<div>
<select name="location">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</div>
<div id="output">
</div>
jQuery
$("select[name=location]").change(function(){
console.log($(this).val()); //value값 가져오기
console.log($("select[name=location] option:selected").text()); //text값 가져오기
});
select박스 값이 바뀔때마다 console.log가 출력되는걸 볼 수 있습니다.
추가적으로 SELECT - OPTION 태그 내부에 VALUE값을 지정을 안하는 경우가 있는데, 이런 경우에는 jQuery .val() 이나 바닐라 .value로 값을 가져올 경우 text값을 가져오게 되니 유의하시기 바랍니다.
반응형
'WEB > jQuery' 카테고리의 다른 글
jQuery - 동그라미 도형 드래그(Draggable) 이벤트 겹침 방지하기 (0) | 2020.07.20 |
---|---|
jQuery - 클릭이벤트 동적 처리하기($("").click(), on('click') 차이) (13) | 2020.04.22 |
jQuery - radio, checkBox값 가져오기, 선택하기, 제어 등 (2) | 2020.02.21 |
jQuery - ajaxSubmit 사용법 및 유의사항(페이지 리로드 현상) (0) | 2020.02.21 |
jQuery - multi select 컴포넌트 없이 멀티 셀렉트 처리 (2) | 2019.11.27 |