How do I get the ID of the DropDownList and pass it to a variable in jQuery?

2

I have the following DropDownList:

<div class="editor-field">
            @Html.DropDownList("ProdutoId", String.Empty)
        </div>

And this jQuery function that when the user presses the button will pick up the selected value and play on a table:

function AddRow()
    {
       var produto = $("ProdutoId")
       $('#tabelaPedidos').append('<tr><td>' + produto  + '</td><td>teste</td></tr>')
    }

But I can not get the DropDownList ID to get the selected value ...

As soon as I populate my DropDownList

ViewBag.ProdutoId = new SelectList(context.Produtos, "ID", "Nome", pedido.ProdutoId);
    
asked by anonymous 06.11.2015 / 19:44

1 answer

2
  

This way you are not selecting the id of DropDown, nor taking the selected value.

Let's break it down. First, to select an element by the id you use this "syntax":

var elemento = $('#IDAqui');

The "old game" sign # indicates this. So to select DropDown you should use this:

var produto = $("#ProdutoId");

However, you have not yet selected the value, let alone the selected item. To do this, you need to filter the selected one and get its value. It would look like your complete code:

function AddRow()
    {
       var produto = $('#ProdutoId option:selected').val();
       $('#tabelaPedidos').append('<tr><td>' + produto  + '</td><td>teste</td></tr>')
    }

In this way you are selecting the element by the id and after getting the option that is selected ( option:selected ) and then getting its value ( .val() ).

    
06.11.2015 / 21:02