I have a form with a select box whose options are pre selected by ajax according to a previous value entered by the user.
I need to add text to these options pre selected ONLY.
for (i in data) {
$("#my_select_box_id").val(data[i][0]).attr('selected',true);
var id_option = data[i][0];
//this following line doesn't work, why do I do wrong here ?
$("#my_select_box_id option[value="id_option"]).html(data[i][1]);
}
Use the
:selectedselector if you want currently selected options.Your code didn’t work because you were prematurely closing the selector string instead of concatenating. This results in an error.
Also, the attribute selector should only work on attributes. I don’t know about jQuery though because they’ve historically diminished the distinction between properties an attributes. So it depends if
.attr()is actually setting the attribute of the property.