Create a jquery option Selected

Asked

Viewed 188 times

0

I’ve seen several posts about it, but none of them were able to help me definitively.

I want to put an option Selected dynamically(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();

So how I put the Joao option as Selected.

I appreciate the help.

  • Instead of you using name in the option, should wear value, which would be the value of the respective option.

1 answer

1


It was not very clear what the dynamic form would be, but just use $("select").val("joao"), follows 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>

  • It wasn’t quite that, but it helped to reformulate my idea. Thanks.

Browser other questions tagged

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