0

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Its works like a charm. So I believe I was missing the cons vals use. Thanks alot @charlietfl Marking as the solution. Appreciate your quick resolution brother.
I did the vals object to cut down on number of if() needed . If that won't work would need more details. Works fine here with duplicates jsfiddle.net/rhputxk4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.