I am adding options to a select tag from a dictionary using jQuery and now I want to set title attribute of each element according to the keys of the dictionary. Can anyone tell me the solution for doing so.
JQuery
function addOptions(){
var dict = {
key1: "val1",
key2: "val2",
key3: "val3",
key4: "val4"
}
$.each(dict, function(val, text){
$('#mySelect').append($('<option></option>').val(val).html(text));
});
HTML
<div class="row" style="padding-top: 20px;">
<div class="col-3">
<select id="mySelect">
<option value="select">--Select--</option>
</select>
<br><br>
<button class="btn btn-sm btn-primary" type="button" id="add" onclick="addOptions()">Add
Values in Dropdown
</button>
</div>
</div>
I tried to select the children of select and then set the title attribute to keys. But all the elements are getting the last key as their title in the same loop. I want all options to have the keys as their title.
$('#mySelect').children('option').attr({"title":val});
2
Answers
for this you can use the addOptions func like this. This can set the title attribute of each option element with the keys of the dictionary
You’ll have less DOM traversal if you start with your select or at least externalize the variable.
End result might look something like