skip to Main Content

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


  1. 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

    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).attr('title', val));
    });
    
    }
    
    Login or Signup to reply.
  2. You’ll have less DOM traversal if you start with your select or at least externalize the variable.

    End result might look something like

    let dict = { key1: "val1", key2: "val2", key3: "val3", key4: "val4" }
    let elem =  $('#mySelect');
    
    
    Object.entries(dict).forEach(([key, val]) => elem.append($('<option></option>')
        .val(key).html(val).attr('title', key)))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="mySelect"></select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search