Heng Sopheak Heng Sopheak - 10 months ago 63
Javascript Question

how to trigger change event on current table rows index in jquery

The Tbody of below table was cloned more than 2 or 3 so I will get more than 2 tbody that contain Class selector .mbody and two of rows in a tbody. However I to used Jquery Change event to get the provinces data when a country selection was selected.

<div class="table-responsive">
<table class="table" id="addressList">
<th>{{ trans('multiple.country') }}</th>
<th>{{ trans('multiple.province') }}</th>
<tbody class="mbody">
<select class="country" name="country[]">
<option value="">-</option>
@foreach($country as $vals)
<option value="{{$vals['iso_code_3']}}"
{{$detail['name']}} {{$vals['id']}}

<select class="provinces" id="provinces" name="provinces[]" style="width: 100%"></select>

<td><a href="#" class="btn btn-info glyphicon glyphicon-plus" onclick="return false"></a></td>

<label> Fields Khmer</label>
<textarea class="form-control" name="fields_kh"></textarea>

<label>Fields English </label>
<textarea class="form-control" name="fields_en"></textarea>


I want to get the provinces data after country was selected on the current rows of this tables

$(document).on('change', 'tbody.mbody tr td', function (e) {
"use strict";
if(typeof country === 'undefined')return;

var provinces = $('.provinces');
var pro = '<option value="">-</option>';

if ($(this).children('select').hasClass('country')) {

var countryId = parseInt($(".country").select2("data").element[0].dataset['id'])

provinces.select2('val', '');

$.each(country, function (inx, vals) {

if (parseInt(vals.id) === countryId) {

$.each(vals.provinces, function (inx, prov) {

pro += '<option value="' + prov.prov_gis + '" data-id="' + prov.id + '"> ' + prov.eng_name + ' </option>';


Select2 don't wrap the provinces contain after append from JS


enter image description here

Answer Source

Change your selectors to select the elements relative to your cloned tbody

  var provinces = $(this).closest('tbody').find('.provinces');
  var countryId = parseInt($(this).closest('tbody').find(".country").select2("data").element[0].dataset['id'])

When you clone the elements destroy the select2 before you clone them and then reinitialize it after the clone to add elements use the select2 syntax

$("#select2").select2('data', {});