Picking the Name and Dropdown ID

0

I have this JavaScript that points the values to DropDown:

$('#Estado').change(function () {
var id = $(Estado).val();

    $(function buscarCidade() {
        //alert(id);
        var url = '@Url.Action("SelecaoCidade", "Chamada")';//url do controller que passará a informação
        $.post(url, { id: id },

             function (data) {//Caso o retorno dê certo
                 //window.alert(data.length);
                 $('#Cidade').children().remove();
                 if (data.length > 0) {
                     $.each(data, function (index, value) {
                         $('#Cidade').append('<option value="' + value.Id + '">' + value.Nome + '</option>');
                     });
                 } else {
                     var novaOpcao = $('<option value=""></option>');
                     $('#Cidade').append(newOption);
                 }//fim if else

             });//fim do post

    });//BuscarCidade

});//Estado

I need to get the name and ID of the cities that were entered, and I tried to use these code snippets to get the id, but it did not roll:

  

var idCid = City.value;

     

var idCid = $ (City) .val ();

     

var idCid = Town.index;

    
asked by anonymous 22.11.2016 / 13:36

2 answers

1

As I read in the comments, json sent as a response to the POST request does not have the id property but CidadeID , so in your code, just replace where you have:

value.id

By:

value.CidadeID

This will assign the id correctly to every option .

    
22.11.2016 / 15:15
1

To get the values from the select you can use:

$("#cidade").change(function(){
  var idCid = $(this).attr("id")
    , valor = $(this).val()
    , nome = $(this).attr("name");
  console.log(idCid, nome, valor);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="cidade" name="cidade">
  <option value="">Selecione</option>
  <option value="SP">São Paulo</option>
  <option value="CT">Curitiba</option>
</select>
    
22.11.2016 / 14:03