Create a selected jquery option

0

I have seen several posts about this, but none have been able to help me definitively.

I'm trying to put a dynamically selected option (db data).

obj.nome = [vitor,joao,carlos]

  dep_option += '<option name ='+obj.nome+'>'+obj.nome+'</option>';
  dep_select = '<select name="select_'+obj.nome+'">'+dep_option+'</select>';
  $('body').html(dep_select).show();

This way I put the option joao as selected.

Thanks for the help.

    
asked by anonymous 25.08.2018 / 18:43

1 answer

1

It was not very clear what the dynamic form would be, but just use $("select").val("joao") , follow a functional code using your example:

var button = $("button")

button.on("click", function() {

  var obj = {};
  obj.nome = ["vitor", "joao", "carlos"];

  var dep_option = "";
  $.each(obj.nome, function(i) {
    dep_option += '<option name=' + obj.nome[i] + '>' + obj.nome[i] + '</option>';
  });

  var dep_select = '<select id="selecionar" name="select_' + obj.nome + '">' + dep_option + '</select>';
  dep_option += dep_option;

  $('body').html(dep_select).show();
  $('#selecionar').val('joao');

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <button>Montar Select!</button>
</body>
    
25.08.2018 / 19:15