Take select description - AJAX

Asked

Viewed 186 times

1

I have this function and need to load the description of the select. In this function I can only load the id, how can I do to in place of x(which is the id) I get the description?

 function myFunction() {
            var x = document.getElementById("mySelect").value;
            document.getElementById("demo").innerHTML = "You selected: " + x;
            var url = "/ContaApagar/CarregaValor";

            $.ajax({
                url: url
                , data: { id: x }
                , type: "POST"
                , datatype: "html"
                , success: function (data) {
                    if (data.resultado > 0) {
                        $("#txtValor").val(data.valor);
                    }
                }
            });


        }

I’d like to play the description on this field:

 <textarea asp-for="ContasApagarVM.ContasApagar.Obs" class="form-control" id="demo"></textarea>

That’s why I need the name, plus value. Here is the controller function Load value.

 [HttpPost]
    public ActionResult CarregaValor( int id, decimal valor)
    {

        var item =  _context.Receitas.Where( r => r.Id == id && r.Tipo == "D").First();
        return Json(new
        {
            valor = item.Valor
           // var teste = valor
        });


    }
  • But the id you are using to make the request, right? You would like to make the request by the description?

  • I edited the question, I need the description to throw it in another field.

  • The description, in this case, would be the text contained in the option of select?

  • Yes, I also put the controller function.

2 answers

2


To get the text of the selected option:

var texto = $("#mySelect option:selected").text();

To play this for the controller, change the date object to:

data: {id: x, text: texto},

Add the additional parameter to the controller

public ActionResult CarregaValor( int id, string text, decimal valor)

To play text in the textarea:

$("#demo").text(texto);

1

In the snippet below, the function retrieves text from <option> chosen within your select. Once this is done, simply save the text to the tag you want!

function myFunction(){
   var x = document.getElementById('mySelect').value
   var texto = $(`#mySelect option:selected`).text()
   $('#demo').text(`You selected ${texto}`)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='mySelect' onchange="myFunction()">
  <option value='1'>Opção 1</option>
  <option value='2'>Opção 2</option>
</select>
<textarea asp-for="ContasApagarVM.ContasApagar.Obs" class="form-control" id="demo"></textarea>

Browser other questions tagged

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