Search code examples
jqueryloopsdropdown

Appending and Selecting option in dropdown from an Array in loop in Jquery


Basically, I have one dropdown in my table. Upon passing a string , I would like to append new rows to the table. After appending new rows to the table, I want to select the option in dropdown on every iteration.

Jquery code:

    array1=['A1','B1','C1'];
    for (i=0;i<array1.length;i++) 
    {
    let newrow = $("<tr>")
    let newcol = $("<td>" +
    "<select class='testdrp'>" + 
    "<option value='1' >AAAA</option>" +
    "<option value='2' >BBBB</option>"+
    "<option value='3' >CCCC</option> </select></td></tr>");
    newrow.append(newcol);
    $("tbody.tablename").append(newrow);

#condition to select option from the dropdown    
            if(array1[i]=='A1') {
                                $(".testdrp option[value='1']").attr("selected", true);
                                }
            else if(array1[i]=='B1') {
                                $(".testdrp option[value='2']").attr("selected", true);
                                }
            else               {
                                $(".testdrp option[value='3']").attr("selected", true);
                              }
    }

However, I am not able to select the correct values for each rows. Is there any proper way for achieving the same here?


Solution

  • Use newrow.find('select') to target the current one within the loop

    const vals = {
      A1: 1,
      B1: 2,
      C1: 3
    },
    array1 = ['A1', 'B1', 'C1'];
    
    for (let i = 0; i < array1.length; i++) {
      let newrow = $("<tr>")
      let newcol = $("<td>" +
        "<select class='testdrp'>" +
        "<option value='1' >AAAA</option>" +
        "<option value='2' >BBBB</option>" +
        "<option value='3' >CCCC</option> </select></td></tr>");
      newrow.append(newcol);
      newrow.find('select.testdrp').val(vals[array1[i]])
    
      $("tbody.tablename").append(newrow);
    
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody class="tablename"></tbody>
    </table>