변경시 선택에서 선택한 값 / 텍스트 가져 오기


102
<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

자바 스크립트에서 선택한 옵션의 값을 가져와야합니다. 선택한 값이나 텍스트를 얻는 방법을 아는 사람이 있습니까? 함수를 작성하는 방법을 알려주십시오. onchange () 함수를 선택하여 할당 했으므로 그 후에 어떻게해야합니까?



1
당신 만 원한다면 valueoption다음 선택한 것을 ... <select onchange="window.alert(this.value);">... option이야 ... </select>나중에 그냥 아무것도 더 가야 ....
S0AndS0

답변:


121

이를 위해 JavaScript 또는 jQuery를 사용하십시오.

JavaScript 사용

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

jQuery 사용

$('#select_id').change(function(){
    alert($(this).val());
})

.value ()는 최신 브라우저에서는 작동하지만 실제로는 오래된 브라우저에서는 작동하지 않습니다. bytes.com/topic/javascript/answers/…
Benissimo

2
@PlayHardGoPro 이것이 선택된 값입니다. 텍스트 (예 : -Select- 또는 Communication)를 원하면 text : select.text또는 jQuery를 사용합니다 select.text().
ricksmt 2013 년

jquery 끝에 세미콜론이 누락되었습니다 ... :)
lindhe

jQuery를 사용하여 $('#select_id option:selected').text()옵션 선택의 텍스트를 반환합니다 .This을 선택 하거나 통신
파울로 Borralho 마틴

1
바닐라 자바 ​​스크립트 접근 방식 : document.getElementById("select_id").onchange = (evt) => { console.log(evt.srcElement.value); }
Spencer

48

인터넷 검색 중이고 이벤트 리스너가 속성이되는 것을 원하지 않는 경우 다음을 사용하십시오.

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});
<select id="my-select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>


33

function test(a) {
    var x = (a.value || a.options[a.selectedIndex].value);  //crossbrowser solution =)
    alert(x);
}
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>


무엇 a.value입니까? 실제로 지원하는 브라우저가 있습니까? 그냥 사용할 수 a.options[a.selectedIndex].value없습니까?
Anonymous

) = 흔들림 감지를 얻을 <@Anonymous
엘 야

28

onchange 기능이 필요하지 않습니다. 한 줄로 값을 가져올 수 있습니다.

document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;

또는 더 나은 가독성을 위해 분할하십시오.

var select_id = document.getElementById("select_id");

select_id.options[select_id.selectedIndex].value;

24

와우, 아직 답변 중 재사용 가능한 솔루션이 없습니다 .. 내 말은 표준 이벤트 처리기는 event인수 만 가져와야하며 ID를 전혀 사용할 필요가 없습니다 .. 다음을 사용합니다.

function handleSelectChange(event) {

    // if you want to support some really old IEs, add
    // event = event || window.event;

    var selectElement = event.target;

    var value = selectElement.value;
    // to support really old browsers, you may use
    // selectElement.value || selectElement.options[selectElement.selectedIndex].value;
    // like el Dude has suggested

    // do whatever you want with value
}

이 핸들러를 각 – 인라인 js와 함께 사용할 수 있습니다.

<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>

jQuery :

jQuery('#select_id').on('change',handleSelectChange);

또는 바닐라 JS 핸들러 설정 :

var selector = document.getElementById("select_id");
selector.onchange = handleSelectChange;
// or
selector.addEventListener('change', handleSelectChange);

그리고 가지고있는 각 select요소 에 대해 이것을 다시 작성할 필요가 없습니다 .

스 니펫 예 :

function handleSelectChange(event) {

    var selectElement = event.target;
    var value = selectElement.value;
    alert(value);
}
<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>


2
훌륭한 솔루션을 받아 들여야합니다. DOM 문서를 참조하지 않고 순수 이벤트 요소를 사용하는 것은 React, Vue 또는 단순한 HTML 형식과 같은 많은 환경에서 작동하는 가장 유연한 방법입니다.
VanDavv

8
let dropdown = document.querySelector('select');
if (dropdown) dropdown.addEventListener('change', function(event) {
    console.log(event.target.value);
});

이 접근 방식은 화살표 기능으로 작업하는 경우 유용합니다.
Franchy

어떤 화살표 함수는 함수 () {},이 같은 일이 교체 할 수 있습니다
러셀 스트라우스

동일하지 않습니다. thisin an arrow 함수는 어휘 환경에서 컨텍스트를 가져 오지만 일반 함수에는 고유 한 것이 있습니다. 이것을
Franchy

6

사용하다

document.getElementById("select_id").selectedIndex

또는 가치를 얻으려면 :

document.getElementById("select_id").value

값을 얻는이 방법은 이전 브라우저에서 작동하지 않습니다. 대신 Danny의 솔루션을 사용하십시오
wlf

6

HTML :

<select onchange="cityChanged(this.value)">
      <option value="CHICAGO">Chicago</option>
      <option value="NEWYORK">New York</option>
</select>

JS :

function cityChanged(city) {
    alert(city);
}

5
<script>
function test(a) {
    var x = a.selectedIndex;
    alert(x);
}
</script>
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>

경고에서 선택한 인덱스의 INT 값을보고 선택 항목을 배열로 취급하면 값을 얻을 수 있습니다.


4

나는 모든 사람에 대해 올렸습니다 궁금해 valuetext에서 얻을 수있는 옵션 <option>및 제안 아무도 label.

그래서 나는 제안하고 있습니다 label 모든 브라우저에서 지원하는 것처럼

얻기 위해 value(다른 사람들이 제안한 것과 동일)

function test(a) {
var x = a.options[a.selectedIndex].value;
alert(x);
}

얻기 위해 option text(예 : 통신 또는-선택-)

function test(a) {
var x = a.options[a.selectedIndex].text;
alert(x);
}

또는 (새로운 제안)

function test(a) {
var x = a.options[a.selectedIndex].label;
alert(x);
}

HTML

<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2" label=‘newText’>Communication</option>
</select>

참고 : option값 2에 대한 위의 HTML 에서 Communication 대신 newTextlabel반환합니다.

또한

참고 : Firefox에서는 레이블 속성을 설정할 수 없습니다 (반환 만 가능).


3

이것은 오래된 질문이지만 사람들이 DOM을 다시 검색하는 대신 이벤트 개체를 사용하여 정보를 검색하는 것을 제안하지 않은 이유를 잘 모르겠습니다.

onChange 함수에서 이벤트 객체를 살펴보기 만하면됩니다. 아래 예제를 참조하십시오.

function test() { console.log(event.srcElement.value); }

http://jsfiddle.net/Corsico/3yvh9wc6/5/

이것이 7 년 전의 기본 행동이 아니었다면 오늘 이것을 찾는 사람들에게 유용 할 수 있습니다.


2

function test(){
  var sel1 = document.getElementById("select_id");
  var strUser1 = sel1.options[sel1.selectedIndex].value;
  console.log(strUser1);
  alert(strUser1);
  // Inorder to get the Test as value i.e "Communication"
  var sel2 = document.getElementById("select_id");
  var strUser2 = sel2.options[sel2.selectedIndex].text;
  console.log(strUser2);
  alert(strUser2);
}
<select onchange="test()" id="select_id">
  <option value="0">-Select-</option>
  <option value="1">Communication</option>
</select>


1

jquery

    $('#select_id').change(function(){
    // selected value 
    alert($(this).val());
    // selected text 
    alert($(this).find("option:selected").text());
})

HTML

<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

0

function test(){
  var sel1 = document.getElementById("select_id");
  var strUser1 = sel1.options[sel1.selectedIndex].value;
  console.log(strUser1);
  alert(strUser1);
  // Inorder to get the Test as value i.e "Communication"
  var sel2 = document.getElementById("select_id");
  var strUser2 = sel2.options[sel2.selectedIndex].text;
  console.log(strUser2);
  alert(strUser2);
}
<select onchange="test()" id="select_id">
  <option value="0">-Select-</option>
  <option value="1">Communication</option>
</select>

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

-1

나는 내 샘플로 설명하려고 노력했지만 도움이되기를 바랍니다. onchange = "test ()"는 필요하지 않습니다 . 라이브 결과를 얻으려면 코드 조각을 실행하십시오.

document.getElementById("cars").addEventListener("change", displayCar);

function displayCar() {
  var selected_value = document.getElementById("cars").value;
  alert(selected_value);
}
<select id="cars">
  <option value="bmw">BMW</option>
  <option value="mercedes">Mercedes</option>
  <option value="volkswagen">Volkswagen</option>
  <option value="audi">Audi</option>
</select>


옵션을 선택하는 것은 암이 아니므로 변경시 클릭 이벤트보다 훨씬 낫습니다.
Riley Carney 2018

@RileyCarney 잘, js 부분에서 함수 이름이 변경 될 때 ui 부분에서 리팩토링 코드를 변경하는 대신 더 우아하고 btw 나는 클릭 이벤트를 보지 못했습니다.

onclick 이벤트 haha를 제거하기 위해 편집했습니다. 그래서 당신이 클릭하기 전에 당신이 차를 위해 그것을 클릭하면 알림을 보냈습니다. edited 7 hours ago적어도 잘 작동하지 않는 코드를 수정했습니다.
Riley Carney
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.