itsource

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

mycopycode 2022. 9. 12. 11:47
반응형

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

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

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

다음과 같은 선택 요소가 지정됩니다.

<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 value = e.value;
var text = e.options[e.selectedIndex].text;

결과:

value == 2
text == "test2"

대화식 예:

var e = document.getElementById("ddlViewBy");
function onChange() {
  var value = e.value;
  var text = e.options[e.selectedIndex].text;
  console.log(value, text);
}
e.onchange = onChange;
onChange();
<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>

플레인 JavaScript:

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

j쿼리:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").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'
}];
var strUser = e.options[e.selectedIndex].value;

이는 정확하며 값을 제공해야 합니다.이게 네가 원하는 문자야?

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

용어에 대해서는 잘 알고 있습니다.

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

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

  • 인덱스 = 0
  • 값 = hello
  • 텍스트 = Hello World

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

소스 링크

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>
var selectedValue = document.getElementById("ddlViewBy").value;

Internet Explorer 전용으로 작성된 코드를 발견한 경우 다음과 같이 표시될 수 있습니다.

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

위의 내용을 Firefox 등에서 실행하면 Internet Explorer에서는 []가 아닌 ()를 사용할 수 있기 때문에 'is not function' 오류가 발생합니다.

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

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

<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" 키워드를 사용할 수 있습니다.이렇게 하면 돔 트리에서 양식을 찾은 다음 양식 내에서 이 요소를 찾을 필요가 없습니다.

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

JavaScript:

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

j쿼리:

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

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

초보자는 ID Atribut이 아닌 NAME Atribut을 사용하여 선택 항목에서 값에 액세스하려고 합니다.모든 양식 요소에는 이름이 필요합니다. ID를 얻기도 전에 말이죠.

이렇게 '아까', '아까', '아까'를 getElementsByName()새로운 개발자도 볼 수 있는 솔루션.

양식 요소의 NB. 이름은 양식을 게시한 후 사용할 수 있도록 고유해야 하지만, DOM을 통해 둘 이상의 요소가 이름을 공유할 수 있습니다.에 ID를 하거나 폼 요소 'ID'를 하는 것을 .my_nth_select_named_x ★★★★★★★★★★★★★★★★★」my_nth_text_input_named_y.

「 」를 getElementsByName:

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

그냥 사용하다

  • $('#SelectBoxId option:selected').text(); 되어 있는

  • $('#SelectBoxId').val();한 인덱스

제가 질문을 제대로 못 맞힌 건지는 모르겠지만, HTML에서 onchange() 이벤트를 사용하세요.

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

// 스크립트 작성

function selectNum(){
    var strUser = document.getElementById("numberToSelect").value;
}

그러면 클릭당 선택 드롭다운에 표시되는 값이 모두 표시됩니다.

jQuery 사용:

$('select').val();

은 아직 있습니다.그 이유는, 「코드의 」, 「코드의 사용법」입니다.idvs 대 name선택한 옵션의 3개의 데이터(인덱스 번호, 값, 텍스트)를 읽어낼 수 있습니다.간단한 크로스 는 세가지 모두를 합니다.

<!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메이크업 용도로 사용해야 합니다.의 목적상, 「 」를 참조해 주세요.name「HTML5」, 「HTML5」, 「HTML5」를 참조해 주세요.마지막으로, 특정 장소에서는 대괄호의 사용에 유의하십시오.앞에서 설명한 바와 같이 모든 장소에서 둥근 것을 사용할 수 있는 것은 (이전 버전의) Internet Explorer뿐입니다.

또 다른 솔루션은 다음과 같습니다.

document.getElementById('elementId').selectedOptions[0].value

하시면 됩니다.querySelector.

예.

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

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

가장 간단한 방법은 다음과 같습니다.

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

동작의 실행 예:

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 변경이 구현됩니다.

나는 이것을 어떻게 달성하느냐에 대해 조금 다른 견해를 가지고 있다.이 작업은 보통 다음과 같은 방법으로 수행합니다(제가 아는 한 모든 브라우저에서 보다 쉽게 수행할 수 있습니다).

<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>

앞의 답변과 마찬가지로 저는 원라이너로서 이렇게 하고 있습니다.선택한 옵션의 실제 텍스트를 가져옵니다.이미 인덱스 번호를 얻는 좋은 예가 있습니다.(그리고 텍스트는 이렇게 보여드리고 싶었어요)

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

드문 경우지만 괄호를 사용해야 하는 경우는 매우 드물 수 있습니다.

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

이 처리가 2라인 버전보다 빠르지는 않을 것 같습니다.가능한 한 코드를 통합하고 싶을 뿐입니다.

유감스럽게도, 이것은 여전히 요소를 두 번 가져옵니다. 이것은 이상적이지 않습니다.요소를 한 번만 잡는 방법이 더 유용하지만, 코드 한 줄로 이것을 하는 것에 대해서는 아직 파악하지 못했습니다.

2015년 Firefox에서는 다음과 같은 기능이 있습니다.

e.discloss.선택된색인

최신 브라우저에서는querySelectorpseudo 클래스를 사용하여 선택한 옵션을 하나의 문으로 가져올 수 있습니다.선택한 옵션에서 필요한 정보를 수집할 수 있습니다.

const opt = document.querySelector('#ddlViewBy option:checked');
// opt is now the selected option, so
console.log(opt.value, 'is the selected value');
console.log(opt.text, "is the selected option's text");
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

다음은 JavaScript 코드행입니다.

var x = document.form1.list.value;

드롭다운 메뉴의 이름이 붙은 리스트가 있다고 가정합니다.name="list"이름 속성을 가진 양식에 포함됨name="form1".

사용하셔야 합니다.querySelector이 목표를 달성합니다.또한 폼 요소에서 가치를 얻는 방법도 표준화됩니다.

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

바이올린: https://jsfiddle.net/3t80pubr/

event.target.value온체인지 콜백이 효과가 있었어요.

해라

ddlViewBy.value                      // value

ddlViewBy.selectedOptions[0].text    // label

console.log( ddlViewBy.value );

console.log( ddlViewBy.selectedOptions[0].text );
<select id="ddlViewBy">
  <option value="1">Happy</option>
  <option value="2">Tree</option>
  <option value="3"  selected="selected">Friends</option>
</select>

이벤트 청취자를 선택 태그 자체에 연결할 수 있습니다. 예:

<script>
  document.addEventListener("DOMContentLoaded", (_) => {
    document.querySelector("select").addEventListener("change", (e) => {
      console.log(e.target.value);
    });
  });
</script>

이 시나리오에서는 모든 옵션의 값 속성이 null이 아닌 것을 확인해야 합니다.

다음은 변경 기능으로 쉽게 수행할 수 있는 방법입니다.

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

<select name="test" id="test" >
    <option value="1" full-name="Apple">A</option>
    <option value="2" full-name="Ball">B</option>
    <option value="3" full-name="Cat" selected>C</option>
</select>

var obj  = document.getElementById('test');
obj.options[obj.selectedIndex].value;  //3
obj.options[obj.selectedIndex].text;   //C
obj.options[obj.selectedIndex].getAttribute('full-name'); //Cat
obj.options[obj.selectedIndex].selected; //true

다음 작업을 수행합니다.document.getElementById('idselect').options.selectedIndex

그러면 0부터 select index 값이 나옵니다.

대부분의 답변은 "이" 선택 메뉴의 값을 가져옵니다.onchange플레인 텍스트 JavaScript 셀렉터를 사용합니다.

예를 들어 다음과 같습니다.

document.getElementById("ddlViewBy").value;

이것은 DRY 어프로치가 아닙니다.

DRY(코드 3줄):

function handleChange(e) {
  let innerText = e.target[e.target.options.selectedIndex].innerText;
  let value = e.target.value;
  /* Do something with these values */
}

첫 번째 선택 옵션을 가져옵니다.

console.log(e.target[0]); /*output: <option value="value_hello">Hello innerText</option>*/

이 아이디어를 염두에 두고 "이" 선택 옵션 항목을 동적으로 반환합니다(By).selectedIndex):

e.target[e.target.options.selectedIndex].innerText;

데모

let log = document.getElementById('log');

function handleChange(e) {
  let innerText = e.target[e.target.options.selectedIndex].innerText;
  let value = e.target.value;
  
  log.innerHTML = `<table>
    <tr><th>value</th><th>innerText</th></tr>
    <tr><td>${value}</td><td>${innerText}</td></tr>
  </table>`;

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css">

<select id="greet" onchange="handleChange(event)">
  <option value="value_hello">Hello innerText</option>
  <option value="value_goodbye">Goodbye innerText</option>
  <option value="value_seeYou">See you... innerText</option>
</select>

<select id="other_select_menu" onchange="handleChange(event)">
  <option value="value_paris">Paris innerText</option>
  <option value="value_ny">New York innerText</option>
</select>

<div id="log"></div>

언급URL : https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript

반응형