0

I have multiple selects in a table and I want to be able to change the options of al the selects on a column when I change the option of the select on the first row. The problem is that the selects are added dynamically. I managed to do this by targeting the first select of each column by it's ID, but I'm looking for a way to do this for all elements at once.

This is the code I have for each column:

$('id-of-the-table-that-already-exists-on-page').on('change','id-of-the-first-select-on-each-column', function() { 
var _value = $(this).val();
var selectId = $(this).attr("id").slice(0, -1);
$('*[id^="' + selectId + '"]').val(_value);

});

Is there a way to add a each function to target all first row selects, instead of targeting each select by it's id?

1 Answers1

0

jQuery's .on() will take a looser selector string as a parameter there. You could target all select elements in the first tr

$( 'id-of-the-table-that-already-exists-on-page' ).on( 'change', 'tr:first-child select', function () {
    // do stuff
} );

var $table = $('#foo');

function add_selects() {
  $table.find('tr:first-child').html(`<select name="bar" id="bar">
<option value="1">Dynamic Option 1</option>
<option value="2">Dynamic Option 2</option>
</select>`);
}

// set listener
$table.on('change', 'tr:first-child select', function(event) {
  console.log('Change! Value is: ' + $(event.target).val());
});

// modify DOM
add_selects();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="foo">
  <tr>
    <td>[select goes here]</td>
  </tr>
  <tr>
    <td>
      <select name="baz" id="baz">
        <option value="a">Option A</option>
        <option value="b">Option B</option>
      </select>
    </td>
  </tr>
</table>

You might have to modify that to accommodate for any thead,tbody, or tfoot elements.

Ito Pizarro
  • 1,607
  • 1
  • 11
  • 21