-
select option value, text 가져오기프로그래밍/Javascript 2020. 11. 1. 12:59
/* jQuery .val(), .text() */ let token = $('select[name=week_company_select]').val(); let name = $('select[name=week_company_select] option:selected').text(); let select_val = $('#id').val(); // 굳이 select 인 거 티 안내도 알아서 가져 옴
/* js .value, .text 선택하고 뒤에 더 처리 */ let target = document.getElementById("selectBox"); let animalSelect = document.querySelector('.animal');
✔ options, selectedIndex 이용해 text, value 가져오기 ( options[2].text 이런 느낌 )
<select name="selectBox" id="selectBox"> <option value="가" selected>A</option> <option value="나">B</option> <option value="다">C</option> </select>
<script type="text/javascript"> let target = document.getElementById("selectBox"); alert('선택된 옵션 text 값=' + target.options[target.selectedIndex].text); alert('선택된 옵션 value 값=' + target.options[target.selectedIndex].value); </script>
✔ options, selectedIndex 이용해 text, value, data-title 가져오기
<select class="animal"> <option data-title="data-cat" value="cat" selected>고양이</option> <option data-title="data-dog" value="dog">강아지</option> <option data-title="data-pig" value="pig">돼지</option> </select>
<script> let animalSelect = document.querySelector('.animal'); let selectEvent = function(){ let text = animalSelect.options[animalSelect.selectedIndex].text; //고양이 let value = animalSelect.options[animalSelect.selectedIndex].value; // cat let dataTitle = animalSelect.options[animalSelect.selectedIndex].getAttribute('data-title') // data-cat } animalSelect.addEventListener("change", selectEvent); </script>
✔ val() 은 select jQuery 셀렉터에 바로 붙이고, text() 는 option:selected 라는 조건을 붙인 다음 출력
$( "#myselect" ).val(); $( "#myselect option:selected" ).text();
<select id="myselect"> <option value="1">Mr</option> <option value="2">Mrs</option> <option value="3">Ms</option> <option value="4">Dr</option> <option value="5">Prof</option> </select>
그래서 내가 쓴 거
function getCompanyList() { var token = $('select[name=week_company_select]').val(); var name = $('select[name=week_company_select] option:selected').text(); }
참고
'프로그래밍 > Javascript' 카테고리의 다른 글
숫자 관련 함수 math.*** (0) 2020.12.23 JS 의 자료형과 형변환 (0) 2020.12.23 일반함수와 화살표 함수의 차이 (0) 2020.12.23 SSR, CSR, SSG (0) 2020.12.23 var, const, let 차이 (0) 2020.11.01