John Davidson

javascript - Yii2 Dynamic Form Select2 Change Event not working from second index


I was trying to create a dynamic form for one of my project. I initialized a ajax request to retrieve value for a field.

<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
'pluginEvents' => [

'select2:select' => 'function(params) {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
"url" : "units",
"type" : "post",
"data" : {itemID: itemVal},
success: function (data) {
error: function (errormessage) {
//do something else
alert("not working");

]); ?>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>

The ajax is working perfectly in the first index of the dynamic form. But unfortunately from the send index, nothing is happening. I checked couple of questions & answers in stackoverflow for the situation, but everything failed.

Can anyone help me to find a solution?

My Answer:
However, I encountered an issue where the change event for the Select2 field was not working for the second index and onwards. After some debugging, I found out that the issue was due to the fact that the change event was not being bound to the newly added Select2 fields.

To fix this issue, I had to re-bind the change event to the Select2 fields after they were dynamically added to the form. Here is the updated code snippet:

// Function to bind change event to Select2 fields
function bindSelect2ChangeEvent() {
$('.dynamic-form').on('change', '.select2-field', function() {
// Your change event logic here

// Function to initialize Select2 for newly added fields
function initSelect2() {

// Function to add new Select2 field dynamically
function addNewSelect2Field() {
// Your logic to add new Select2 field here

// Re-bind change event to Select2 fields

// Initialize Select2 for existing fields

// Bind change event to existing Select2 fields

By re-binding the change event to the Select2 fields after they are dynamically added, the change event should now work for all Select2 fields, including those added dynamically.

Rate this post

3 of 5 based on 4022 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us