Paste description select - AJAX

1

I have this function and need to load the same description as select. In this function I can just load the id, how can I do it in place of the x (what is the id) I take 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 would like to play the description in this field:

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

That's why I need the name, besides the value. Here is the function of the LoadValue controller.

 [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
        });


    }
    
asked by anonymous 05.07.2018 / 20:31

2 answers

2

To get the text of the selected option:

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

To throw this to the controller, change the data object to:

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

Add the additional parameter in the controller

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

To play text in textarea:

$("#demo").text(texto);
    
05.07.2018 / 20:40
1

In the snippet below, the function retrieves the text of the <option> chosen within your select. Once you've done that, just save the text in 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><selectid='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>
    
05.07.2018 / 20:46