0

With this HTML for a DropDownList (that relates to a model with simple int Id and string Name)

<select id="Powder_Id" name="Powder.Id">
    <option value="1">50g</option>
    <option value="2">100g</option>
</select>

I can get the selected option key (Id) using this JS:

function save() {
    var payload = {
        DdlId: $("#Powder_Id").val()  // e.g. 1 or 2
    };

But how can I get the selected option value (Name)? Something like SelectedValue in place of val()?:

function saveSummary() {
    var p = {
        Powder: { Id: $("#Powder_Id").SelectedValue } // e.g. "50g" or "100g"
    }

Ideally I want to recreate the model as an object to pass to an ajax call, but to do that I need both the Id and Name values.

jamheadart
  • 5,047
  • 4
  • 32
  • 63
  • [`option`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement) elements don't have keys and values. They have values and text. – Heretic Monkey Apr 27 '20 at 12:16

1 Answers1

1

You can get selected text by

$("#Powder_Id option:selected").text();

 var selectedText = $("#Powder_Id option:selected").text();
 console.log(selectedText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Powder_Id" name="Powder.Id">
    <option value="1">50g</option>
    <option value="2">100g</option>
</select>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62