Programing

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

lottogame 2020. 12. 10. 08:24
반응형

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


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

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


이를 위해 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());
})

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;

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>


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

document.getElementById('select_id').addEventListener('change', function(){
    this.value;
});

와우, 아직 답변 중 재사용 가능한 솔루션이 없습니다 .. 내 말은 표준 이벤트 처리기는 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>


사용하다

document.getElementById("select_id").selectedIndex

또는 가치를 얻으려면 :

document.getElementById("select_id").value

<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 값을보고 선택 항목을 배열로 취급하면 값을 얻을 수 있습니다.


HTML :

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

JS :

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

나는 모든 사람에 대해 올렸습니다 궁금해 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반환합니다.

또한

Note: It is not possible to set the label property in Firefox (only return).


This is an old question, but I am not sure why people didn't suggest using the event object to retrieve the info instead of searching through the DOM again.

Simply go through the event object in your function onChange, see example bellow

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

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

Might be useful to people looking this up today if this wasn't default behavior 7 years ago


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>


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;

I have tried to explain with my own sample, but I hope it will help you. You don't need onchange="test()" Please run code snippet for getting a live result.

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>


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

참고URL : https://stackoverflow.com/questions/5416767/get-selected-value-text-from-select-on-change

반응형