Heng Sopheak Heng Sopheak - 19 days ago 11
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">
<thead>
<tr>
<th>{{ trans('multiple.country') }}</th>
<th>{{ trans('multiple.province') }}</th>
</tr>
</thead>
<tbody class="mbody">
<tr>
<td>
<select class="country" name="country[]">
<option value="">-</option>
@foreach($country as $vals)
<option value="{{$vals['iso_code_3']}}"
data-id="{{$vals['id']}}">
{{$detail['name']}} {{$vals['id']}}
</option>
@endforeach
</select>
</td>

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

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

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

<td>
<label>Fields English </label>
<textarea class="form-control" name="fields_en"></textarea>
</td>
</tr>
</tbody>
</table>
</div>


Javascript:

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>';
});
}
});

provinces.empty().append(pro);
}
});


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

provinces.empty().append(pro);


enter image description here

Answer

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', {});