How to take the Dropdownlist ID and move to a jQuery variable?

Asked

Viewed 1,247 times

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 in a table:

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

But I can’t get the Dropdownlist ID to get the selected value...

As soon as I fill out my Dropdownlist

ViewBag.ProdutoId = new SelectList(context.Produtos, "ID", "Nome", pedido.ProdutoId);
  • which html is generated with the command "@Html.Dropdownlist("Produtoid", String.Empty)"?

  • A dropdownlist with my products loaded...

1 answer

2

That way you’re not selecting the id dropdown, and not even taking the selected value.

Let’s go in pieces. First, to select an element by id you use this "syntax":

var elemento = $('#IDAqui');

The sign of "tic-tac-toe" # indicates this. So to select the Dropdown you should use this:

var produto = $("#ProdutoId");

However, you have not yet selected the value, much less the selected item. For this, you need to filter the selected one and after obtaining its value. That would be your complete code:

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

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

  • That’s exactly what I want to do...only that the way you said I’m taking a number for example 5...the "selectedIndex" inves of the "selectedValue" will I fill this dropdownlist wrong ? I’ll edit in the code as I’m doing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.