JavaScript를 사용하여 드롭 다운 목록에서 선택된 값 가져 오기


1784

JavaScript를 사용하여 드롭 다운 목록에서 선택한 값을 얻으려면 어떻게합니까?

아래 방법을 시도했지만 모두 값 대신 선택한 색인을 반환합니다.

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

답변:


2927

다음과 같은 select 요소가있는 경우 :

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

이 코드를 실행 :

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

만들 것 strUser수 2. 실제로 원하는 것이 인 test2경우 다음을 수행하십시오.

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

어느 것이 strUser될 것인가test2


13
@ R11G, use onchange:)
— AlexJaa

142
var strUser = e.options[e.selectedIndex].value;왜 안돼var strUser = e.value ?
— The Red Pea

18
@ TheRedPea— 아마도이 답변이 작성되었을 때 고대 버전의 Netscape Navigator를 수용해야 할 가능성이 있었기 때문에 단일 선택의 가치에 액세스하는 동일한 방법이 사용 되었기 때문일 것입니다. 그러나 나는 단지 그것에 대해 추측하고 있습니다. ;-)
— RobG

12
:이처럼 사용할var e = document.getElementById("ddlViewBy").value;
— Fathur Rohim

3
해야 e.target.options[e.target.selectedIndex].text모르는 이유는 여기에 모든 대답에 그것의 잘못 ..
— 오지

372

일반 자바 스크립트 :

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery :

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").val(); // The value of the selected option

AngularJS : ( http://jsfiddle.net/qk5wwyct ) :

// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// JavaScript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'
}];

1
이것을 시도 할 때 드롭 다운의 모든 옵션 텍스트를 다시 가져 오기 때문에 뭔가 잘못하고 있어야합니다.
— 케빈

6
이것은 다른 방식으로 나를 위해 일했습니다. $ ( "# ddlViewBy : selected"). val () 선택하지 않고
— Ruwantha

1
element.options[e.selectedIndex].value해야element.options[element.selectedIndex].value
— 크리스토퍼

여전히 유용합니다-변형 / 언어를 작성해 주셔서 감사합니다! 이제 Office JS API 드롭 다운에 해당하는 내용 만 알고 있다면 ...
— Cindy Meister

해야 e.target.options[e.target.selectedIndex].text모르는 이유는 여기에 모든 대답에 그것의 잘못 ..
— 오지

174
var strUser = e.options[e.selectedIndex].value;

이것은 정확하며 가치를 제공해야합니다. 당신이 뒤 따르는 텍스트입니까?

var strUser = e.options[e.selectedIndex].text;

따라서 용어에 대해 명확합니다.

<select>
    <option value="hello">Hello World</option>
</select>

이 옵션은 다음과 같습니다.

  • 인덱스 = 0
  • 가치 = 안녕하세요
  • 텍스트 = Hello World

1
Javascript의 ".value"가 나에게 값을 반환해야한다고 생각했지만 ".text"만 asp.net의 .SelectedValue가 반환하는 것으로 반환합니다. 예를 들어 주셔서 감사합니다!
— Fire Hand

1
그렇습니다-옵션의 가치를 그대로 유지하십시오. 더 간단합니다-위의 사람은 초기 모호성을 보완하기 위해 더 많은 코드를 작성해야합니다.
— Andrew Koper

해야 e.target.options[e.target.selectedIndex].text모르는 이유는 여기에 모든 대답에 그것의 잘못 ..
— 오지

62

다음 코드는 JavaScript를 사용하여 입력 / 선택 필드에서 값을 가져 오거나 입력하는 것과 관련된 다양한 예제를 보여줍니다.

소스 링크

자바 스크립트 및 jQuery 데모 작업

여기에 이미지 설명을 입력하십시오

여기에 이미지 설명을 입력하십시오

 <select id="Ultra" onchange="run()">  <!--Call run() function-->
     <option value="0">Select</option>
     <option value="8">text1</option>
     <option value="5">text2</option>
     <option value="4">text3</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
TextBox2<br>
<input type="text" id="rtt"  placeholder="Write Something !" onkeyup="up()">

다음 스크립트는 선택한 옵션의 값을 가져 와서 텍스트 상자에 넣습니다 1

<script>
    function run() {
        document.getElementById("srt").value = document.getElementById("Ultra").value;
    }
</script>

다음 스크립트는 텍스트 상자 2에서 값을 가져오고 그 값으로 경고합니다.

<script>
    function up() {
        //if (document.getElementById("srt").value != "") {
            var dop = document.getElementById("srt").value;
        //}
        alert(dop);
    }
</script>

다음 스크립트는 함수에서 함수를 호출합니다.

<script>
    function up() {
        var dop = document.getElementById("srt").value;
        pop(dop); // Calling function pop
    }

    function pop(val) {
        alert(val);
    }?
</script>

onchange=run(this.value)또는 (this.text)더 유익 할 수 있습니다.
— Berci


22

Internet Explorer 용으로 작성된 코드를 실행하는 경우 다음과 같이 표시 될 수 있습니다.

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

Firefox 등에서 위의 내용을 실행하면 Internet Explorer에서 [] 대신 ()를 사용하여 벗어날 수 있기 때문에 '기능이 아닙니다'오류가 발생합니다.

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

올바른 방법은 대괄호를 사용하는 것입니다.


19
<select id="Ultra" onchange="alert(this.value)"> 
 <option value="0">Select</option>
 <option value="8">text1</option>
 <option value="5">text2</option>
 <option value="4">text3</option>
</select>

모든 입력 / 양식 필드는 요소 내부에서 액세스 할 때 "this"키워드를 사용할 수 있습니다. 이를 통해 돔 트리에서 양식을 찾은 다음이 요소를 양식 안에 배치 할 필요가 없습니다.


순서대로 설명하겠습니다.
— Peter Mortensen

14

초보자는 ID 속성이 아닌 NAME 속성을 사용하여 선택 항목의 값에 액세스하려고합니다. 우리는 모든 양식 요소가 ID를 받기 전에도 이름이 필요하다는 것을 알고 있습니다.

그래서 나는 getElementByName()새로운 개발자들도 볼 수 있는 솔루션을 추가하고 있습니다.

NB. 양식 요소의 이름은 게시 된 양식을 사용할 수 있으려면 고유해야하지만 DOM은 둘 이상의 요소가 이름을 공유하도록 허용 할 수 있습니다. 따라서 양식 요소 이름 my_nth_select_named_x및 으로 명시 적이거나 명시적일 수있는 경우 양식에 ID를 추가하는 것이 좋습니다 my_nth_text_input_named_y.

사용 예 getElementByName:

var e = document.getElementByName("my_select_with_name_ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

작동하지 않음 my_select_with_name_ddlViewBy 같은 배열의 경우 my_select_with_name_ddlViewBy []
— zeuf

14

JavaScript 또는 jQuery를 사용하여이를 수행하는 방법에는 두 가지가 있습니다.

자바 스크립트 :

var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;

alert (getValue); // This will output the value selected.

또는

var ddlViewBy = document.getElementById('ddlViewBy');

var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;

var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;

alert (value); // This will output the value selected

alert (text); // This will output the text of the value selected

jQuery :

$("#ddlViewBy:selected").text(); // Text of the selected value

$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'

12

그냥 사용

  • $('#SelectBoxId option:selected').text(); 나열된 텍스트를 얻기 위해

  • $('#SelectBoxId').val(); 선택된 인덱스 값을 얻기 위해


5
이것은 OP의 질문에 대답하지 않는 jQuery를 사용합니다.
— David Meza

9

이전 답변은 가능성, 코드의 직관적 성 및 idvs 의 사용으로 인해 여전히 개선의 여지가 남아 있습니다 name. 선택한 옵션의 세 가지 데이터 (색인 번호, 값 및 텍스트)를 읽을 수 있습니다. 이 간단한 크로스 브라우저 코드는 세 가지를 모두 수행합니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo GetSelectOptionData</title>
</head>
<body>
    <form name="demoForm">
        <select name="demoSelect" onchange="showData()">
            <option value="zilch">Select:</option>
            <option value="A">Option 1</option>
            <option value="B">Option 2</option>
            <option value="C">Option 3</option>
        </select>
    </form>

    <p id="firstP">&nbsp;</p>
    <p id="secondP">&nbsp;</p>
    <p id="thirdP">&nbsp;</p>

    <script>
    function showData() {
        var theSelect = demoForm.demoSelect;
        var firstP = document.getElementById('firstP');
        var secondP = document.getElementById('secondP');
        var thirdP = document.getElementById('thirdP');
        firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
        secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
        thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
    }
     </script>
</body>
</html>

라이브 데모 : http://jsbin.com/jiwena/1/edit?html,output .

id메이크업 목적으로 사용해야합니다. 기능적 형태의 목적을 위해 nameHTML5에서도 유효하며 여전히 사용해야합니다. 마지막으로 특정 장소에서 대괄호와 둥근 대괄호를 사용하십시오. 이전에 설명했듯이 Internet Explorer는 (이전 버전) Internet Explorer 만 모든 곳에서 사용할 수 있습니다.




6

작동 방식의 실행 예 :

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

document.write("<br />Selected option Value: "+ val1);
document.write("<br />Selected option Text: "+ txt);
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2">test2</option>
  <option value="3"  selected="selected">test3</option>
</select>

참고 : 드롭 다운이 변경 될 때 값이 변경되지 않습니다. 해당 기능이 필요한 경우 onClick 변경이 구현됩니다.


사용한 후 코드를 새로 고쳐야하는 방법을 보여주는 좋은 답변입니다!
— 사용자가 아닌 사용자

5

사용할 수 있습니다 querySelector.

예 :

var myElement = document.getElementById('ddlViewBy');

var myValue = myElement.querySelector('[selected]').value;

5

나는 이것을 달성하는 방법에 대해 약간 다른 견해를 가지고 있습니다. 나는 보통 다음과 같은 접근 방식 으로이 작업을 수행합니다 (더 쉬운 방법이며 내가 아는 한 모든 브라우저에서 작동합니다).

<select onChange="functionToCall(this.value);" id="ddlViewBy">
  <option value="value1">Text one</option>
  <option value="value2">Text two</option>
  <option value="value3">Text three</option>
  <option value="valueN">Text N</option>
</select>


4

이전 답변과 함께하기 위해 이것이 내가 하나의 라이너로하는 방법입니다. 선택한 옵션의 실제 텍스트를 가져 오기위한 것입니다. 이미 색인 번호를 얻는 좋은 예가 있습니다. (그리고 본문에서는 방금이 방법을 보여주고 싶었습니다)

let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text

드문 경우에 괄호를 사용해야 할 수도 있지만 이는 매우 드 would니다.

let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;

나는 이것이 두 줄 버전보다 빨리 처리되는 것을 의심합니다. 코드를 최대한 많이 통합하고 싶습니다.

불행히도 이것은 여전히 ​​요소를 두 번 가져 오는데 이는 이상적이지 않습니다. 한 번만 요소를 잡는 방법이 더 유용하지만 한 줄의 코드 로이 작업을 수행하는 것과 관련하여 아직 알지 못했습니다.


3

JavaScript 코드 라인은 다음과 같습니다.

var x = document.form1.list.value;

드롭 다운 메뉴가 list name="list"이고 이름이 attribute 인 양식에 포함되어 있다고 가정 합니다 name="form1".


OP는 다음과 같이 작동하지 않는다고 말했다. "아래 방법을 시도했지만 모두 선택한 값 대신 값을 반환합니다. var as = document.form1.ddlViewBy.value;..."
— 사용자가 아닌 사용자

2

당신은 사용해야 querySelector이것을 달성 할 수 있습니다. 또한 양식 요소에서 가치를 얻는 방법을 표준화합니다.

var dropDownValue = document.querySelector('#ddlViewBy').value;

피들 : https://jsfiddle.net/3t80pubr/


1

질문이 맞지 않는 사람인지는 모르겠지만, 그것은 저에게 효과적이었습니다. 예를 들어 HTML에서 onchange () 이벤트 사용하기.

<select id="numberToSelect" onchange="selectNum">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

// 자바 스크립트

function sele(){
    var strUser = numberToSelect.value;
}

클릭당 선택 드롭 다운 값이 무엇이든 제공됩니다.


1

이를 수행하는 가장 간단한 방법은 다음과 같습니다.

var value = document.getElementById("selectId").value;

그는 값이 아니라 선택 상자에 표시된 텍스트를 원합니다
— Thanasis

0

다음은 onchange 함수에서 쉽게 수행 할 수있는 방법입니다.

event.target.options[event.target.selectedIndex].dataset.name


1
단순성에 대한 이야기, 나는 생각했다 이 대신 event.target
— 기독교 Læirbag


-1

시험

ddlViewBy.value                      // value

ddlViewBy.selectedOptions[0].text    // label


-1

여러 옵션이있는 드롭 다운 메뉴를 만드십시오 (원하는만큼!)

<select>
  <option value="giveItAName">Give it a name
  <option value="bananaShark">Ridiculous animal
  <ooption value="Unknown">Give more options!
</select>

나는 약간 유쾌했다. 다음은 코드 스 니펫입니다.

<select>
  <option value="RidiculousObject">Banana Shark
  <option value="SuperDuperCoding">select tag and option tag!
  <option value="Unknown">Add more tags to add more options!
</select>
<h1>Only 1 option (Useless)</h1>
<select>
  <option value="Single">Single Option
</select>  

예, 스 니펫이 작동했습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.