简体   繁体   中英

get value of dropdown not just ID

I am trying to populate a textfield with the value of whatever is in my dropdown box. Now all I get right now is the ID for the selected item, first in the list is 1, etc.

I know its got to be something stupid that I am missing but I can't see it at the moment.

How do I get the value of the selected item, instead of the ID?

Here is what I have so far, #id_maturity_letter is the dropdown and #message_text is the textarea I am trying to populate.

$("#id_maturity_letter").change(function() {
    var id = $(this).val();
    $('#message_text').val($('#id_maturity_letter').val());
    $.getJSON('', {id:id}, function(json) {

    });

}); 

Your code is correct, be sure that your html is created as you wish:

<select id='id_maturity_letter'>
   <option id='1' value='1'>one</option>
   <option id='2' value='2'>two</option>
   <option id='3' value='3'>three</option>
</select>

will of course return a value that is equal to the id

So if you need the text:

 $("#message_text").val( $("option:selected", this).text() );

If I understand your question correctly, you want the text of the selected option instead of its value. If that's actually the case, you can match the selected <option> element with the :selected selector, then call text() on the resulting object:

$("#id_maturity_letter").change(function() {
    var id = $(this).val();
    $("#message_text").val($("option:selected", this).text());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM