0

I am trying to select programmatically an option from a HTML Select which is filled dynamically by code.

The selected is filled with a for:

for(var i =0; i< valores.length ; i++)
{
    var opcion= "<option value="+valores[i]['id_estado']+">"+valores[i]['nombre_estado']+"</option>";
    selectEstado.append(opcion);    
}

and then select a option with:

$("#select_estado option[value='"+valores[0]['estado']+"']").attr('selected', true);

but when I do the select locates in the value=0, any ideas?

Alan Larimer
  • 589
  • 8
  • 24

1 Answers1

0

I don't know how you did declare your valores array, so I felt free to declare a new array that takes the keys you used in your question.

So if you declared your array the same way I did then you shouldn't use this syntax valores[i]['id_estado'] but you should use this one valores[i].id_estado

Otherwise, to select an option by it value you should use the simple function val().

Finally I support my answer with this question: Set select option 'selected', by value

$(function(){

var valores={ 
0:{'id_estado':1,'nombre_estado':3},
1:{'id_estado':5,'nombre_estado':2},
2:{'id_estado':20,'nombre_estado':1}
        };
        
 var count=Object.keys(valores).length;
for(var i =count-1; i>= 0 ; i--)
{
    var opcion= "<option value="+valores[i].id_estado+">"+valores[i].nombre_estado+"</option>";
    $("#select_estado").append(opcion);      
}

$("button").on("click",function(){
$("select").val(valores[1].id_estado);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <select id="select_estado"></select>
 <button type="button" >Select</button>

Hope it helps !

Mehdi Bouzidi
  • 1,937
  • 3
  • 15
  • 31