your programing

jQuery 드롭 다운에서 선택한 옵션 가져 오기

lovepro 2020. 9. 27. 13:32
반응형

jQuery 드롭 다운에서 선택한 옵션 가져 오기


일반적으로 $("#id").val()선택한 옵션의 값을 반환하는 데 사용 하지만 이번에는 작동하지 않습니다. 선택한 태그에는 ID가 있습니다.aioConceptName

HTML 코드

<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

드롭 다운 옵션의 경우 다음과 같은 것을 원할 것입니다.

var conceptName = $('#aioConceptName').find(":selected").text();

그 이유 val()는 옵션을 클릭해도 드롭 다운의 값이 변경되지 않고 드롭 다운 :selected자식선택한 옵션에 속성이 추가되기 때문 입니다.


각 옵션의 값을 설정합니다.

<select id="aioConceptName">
    <option value="0">choose io</option>
    <option value="1">roma</option>
    <option value="2">totti</option>
</select>

$('#aioConceptName').val()속성을 .val()반환 하기 때문에 작동하지 않았습니다 value. 제대로 작동하려면 value각에 속성을 설정해야합니다 <option>.

이제 다른 사람들이 제안하는 $('#aioConceptName').val()이 모든 :selected부두 대신 전화 걸 수 있습니다.


나는이 질문을 우연히 발견하고 Elliot BOnneville의 답변에 대한 더 간결한 버전을 개발했습니다.

var conceptName = $('#aioConceptName :selected').text();

또는 일반적으로 :

$('#id :pseudoclass')

이것은 추가 jQuery 호출을 저장하고 한 번에 모든 것을 선택하며 더 명확합니다 (내 의견).


가치를 위해 이것을 시도하십시오 ...

$("select#id_of_select_element option").filter(":selected").val();

또는 이것은 텍스트를 위해 ...

$("select#id_of_select_element option").filter(":selected").text();

이벤트 컨텍스트에있는 경우 jQuery에서 다음
$(this).find('option:selected')과 같이 사용하여 선택한 옵션 요소를 검색 할 수 있습니다 .

$('dropdown_selector').change(function() {
    //Use $option (with the "$") to see that the variable is a jQuery object
    var $option = $(this).find('option:selected');
    //Added with the EDIT
    var value = $option.val();//to get content of "value" attrib
    var text = $option.text();//to get <option>Text</option> content
});

편집하다

PossessWithin 에서 언급했듯이 내 대답은 다음 질문에 대한 대답입니다. 선택한 "옵션"을 선택하는 방법.

다음으로 옵션 값을 얻으려면 option.val().


평범한 오래된 자바 스크립트 사용을 고려해 보셨습니까?

var box = document.getElementById('aioConceptName');

conceptName = box.options[box.selectedIndex].text;

JavaScript로 옵션 텍스트 / 값 가져 오기를 참조하십시오.


$('#aioConceptName option:selected').val();

선택의 값 (텍스트가 아님) 읽기 :

var status = $("#Status").val();
var status = $("#Status")[0].value;
var status = $('#Status option:selected').val();

선택을 비활성화하는 방법은 무엇입니까? 두 변형 모두 다음을 사용하여 값을 변경할 수 있습니다.

사용자는 드롭 다운과 상호 작용할 수 없습니다. 그리고 그는 다른 옵션이 무엇인지 알지 못합니다.

$('#Status').prop('disabled', true);

사용자는 드롭 다운에서 옵션을 볼 수 있지만 모두 비활성화됩니다.

$('#Status option').attr('disabled', true);

경우은보다 작은 jQuery 버전 $("#Status").val() 에서만 작동 합니다 1.9.0. 다른 모든 변형이 작동합니다.

비활성화 된 선택을 업데이트하는 방법은 무엇입니까?

코드 뒤에서 여전히 선택한 값을 업데이트 할 수 있습니다. 사용자에 대해서만 비활성화됩니다.

$("#Status").val(2);

경우에 따라 이벤트를 시작해야 할 수도 있습니다.

$("#Status").val(2).change();

<select id="form-s" multiple="multiple">
    <option selected>city1</option>
    <option selected value="c2">city2</option>
    <option value="c3">city3</option>
</select>   
<select id="aioConceptName">
    <option value="s1" selected >choose io</option>
    <option value="s2">roma </option>
    <option value="s3">totti</option>
</select>
<select id="test">
    <option value="s4">paloma</option>
    <option value="s5" selected >foo</option>
    <option value="s6">bar</option>
</select>
<script>
$('select').change(function() {
    var a=$(':selected').text(); // "city1city2choose iofoo"
    var b=$(':selected').val();  // "city1" - selects just first query !
    //but..
    var c=$(':selected').map(function(){ // ["city1","city2","choose io","foo"]
        return $(this).text();
    }); 
    var d=$(':selected').map(function(){ // ["city1","c2","s1","s5"]
        return $(this).val();
    });
    console.log(a,b,c,d);
});
</script>

다음 구문을 사용해야합니다.

var value = $('#Id :selected').val();

따라서 다음 코드를 시도하십시오.

var values = $('#aioConceptName :selected').val();

Fiddle에서 테스트 할 수 있습니다 : http://jsfiddle.net/PJT6r/9/

이 게시물 에서이 답변에 대해 참조하십시오.


jQuery를 사용하여 change이벤트를 추가하고 해당 핸들러 내에서 선택한 값 또는 텍스트를 가져옵니다.

선택한 텍스트가 필요한 경우 다음 코드를 사용하십시오.

$("#aioConceptName").change(function () {
    alert($("#aioConceptName :selected").text())
});

또는 선택한 값이 필요한 경우 다음 코드를 사용하십시오.

$("#aioConceptName").change(function () {
    alert($("#aioConceptName :selected").attr('value'))
});

Use the jQuery.val() function for select elements, too:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

$(function() {
  $("#aioConceptName").on("change", function() {
    $("#debug").text($("#aioConceptName").val());
  }).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<select id="aioConceptName">
  <option>choose io</option>
  <option>roma</option>
  <option>totti</option>
</select>
<div id="debug"></div>


For anyone who found out that best answer don't work.

Try to use:

  $( "#aioConceptName option:selected" ).attr("value");

Works for me in recent projects so it is worth to look on it.


Just this should work:

var conceptName = $('#aioConceptName').val();

Straight forward and pretty easy:

Your dropdown

<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

Jquery code to get the selected value

$('#aioConceptName').change(function() {
    var $option = $(this).find('option:selected');

    //Added with the EDIT
    var value = $option.val(); //returns the value of the selected option.
    var text = $option.text(); //returns the text of the selected option.
});

You can try to debug it this way:

console.log($('#aioConceptName option:selected').val())

If you want to grab the 'value' attribute instead of the text node, this will work for you:

var conceptName = $('#aioConceptName').find(":selected").attr('value');

I hope this also helps to understand better and helps try this below, $('select[id="aioConceptName[]"] option:selected').each(function(key,value){ options2[$(this).val()] = $(this).text(); console.log(JSON.stringify(options2)); });
to more details please http://www.drtuts.com/get-value-multi-select-dropdown-without-value-attribute-using-jquery/


try to this one

$(document).ready(function() {

    $("#name option").filter(function() {
        return $(this).val() == $("#firstname").val();
    }).attr('selected', true);

    $("#name").live("change", function() {

        $("#firstname").val($(this).find("option:selected").attr("value"));
    });
});


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name"> 
<option value="">Please select...</option> 
<option value="Elvis">Elvis</option> 
<option value="Frank">Frank</option> 
<option value="Jim">Jim</option> 
</select>

<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">

For get value of tag selected:

 $('#id_Of_Parent_Selected_Tag').find(":selected").val();

And if you want to get text use this code:

 $('#id_Of_Parent_Selected_Tag').find(":selected").text();

For Example => i have this tag selected :

<div id="id_Of_Parent_Selected_Tag">
<select >
        <option value="1">CR7</option>
        <option value="2">MESSI</option>
    </select>
</div>
<script>
 $('#id_Of_Parent_Selected_Tag').find(":selected").val();//OUTPUT:1 OR 2
 $('#id_Of_Parent_Selected_Tag').find(":selected").text();//OUTPUT:CR7 OR MESSI
</script>

You can use $("#drpList").val();


Usually you'd need to not only get the selected value, but also run some action. So why not avoid all the jQuery magic and just pass the selected value as an argument to the action call?

<select onchange="your_action(this.value)">
   <option value='*'>All</option>
   <option ... />
</select>

You can select using exact selected option : Below will give innerText

$("select#aioConceptName > option:selected").text()

While below will give you value.

$("select#aioConceptName > option:selected").val()

to fetch a select with same class= name you could do this, to check if a select option is selected.

var bOK = true;
$('.optKategorien').each(function(index,el){
    if($(el).find(":selected").text() == "") {
        bOK = false;
    }
});

I had the same issue and I figured out why it was not working on my case
The html page was divided into different html fragments and I found that I have another input field that carries the same Id of the select, which caused the val() to be always empty
I hope this saves the day for anyone who have similar issue.


to use $("#id").val, You should add a value to the option like this :

<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option value="choose">choose io</option>
</select>

else, You can use

   $("#aioConceptName").find(':selected').text();

I wish that helps ..


$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);

Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.


Probably your best bet with this kind of scenario is to use jQuery's change method to find the currently selected value, like so:

$('#aioConceptName').change(function(){

   //get the selected val using jQuery's 'this' method and assign to a var
   var selectedVal = $(this).val();

   //perform the rest of your operations using aforementioned var

});

I prefer this method because you can then perform functions for each selected option in a given select field.

Hope that helps!

참고URL : https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown

반응형