Ask Your Question
0

How can I use an array from an ajax call and jquery to fill a select/dropdownlist in every cell of a table column?

asked 2023-05-08 12:32:54 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-08 12:44:02 +0000

woof gravatar image

Assuming you have an HTML table like this:

<table id="myTable">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><select></select></td>
      <td><select></select></td>
      <td><select></select></td>
    </tr>
    <tr>
      <td><select></select></td>
      <td><select></select></td>
      <td><select></select></td>
    </tr>
  </tbody>
</table>

And you have an AJAX call that returns an array of options like this:

$.ajax({
  url: 'your-url',
  dataType: 'json',
  success: function(data) {
    // data is an array of options
  }
});

You can fill the selects in the table column using jQuery like this:

// get all the selects in the first column
var selects = $('#myTable tbody tr td:nth-child(1) select');

// loop through each select
selects.each(function() {
  // get a reference to the select
  var select = $(this);

  // loop through the options and add them to the select
  $.each(data, function(index, value) {
    // create an option element and add it to the select
    var option = $('<option>').text(value);
    select.append(option);
  });
});

This code gets all the selects in the first column of the table, loops through them, and adds the options from the AJAX call to each select.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-08 12:32:54 +0000

Seen: 11 times

Last updated: May 08 '23