John Davidson

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

0 comments
Message:


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, "");
$.ajax({
"url" : "units",
"type" : "post",
"data" : {itemID: itemVal},
success: function (data) {
console.log(data);
console.log(attrID);
$("#reqitems-"+attrID+"-rt_unit").val(data);
},
error: function (errormessage) {
//do something else
alert("not working");

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

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:

javascript
// 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() {
$('.select2-field').select2();
}

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

// Re-bind change event to Select2 fields
bindSelect2ChangeEvent();
}

// Initialize Select2 for existing fields
initSelect2();

// Bind change event to existing Select2 fields
bindSelect2ChangeEvent();


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

Comments




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