yii2-dynamicform icon indicating copy to clipboard operation
yii2-dynamicform copied to clipboard

onChange not working for dynamically added elements

Open swati-clarion opened this issue 8 years ago • 12 comments

I was trying to add dependent dropdown box on change of first dropdown. But the onChange event works for only first elements in widget. If new elements are appended , then same onChange code is added to clone. New dynamic id is not allotted. Hence, all dropdowns keep updating the very first dependent dropdown instead of their adjacent dropdowns.

I had to add a jquery function for onchange event and then get id of dependent dropdown to fill data using onchange of its relative first dropdown.

swati-clarion avatar May 31 '16 20:05 swati-clarion

May I see your JS? since its dynamic use class instead of ID.. cloning Issue its on the js side, what I did is preventing the multiple fire of same class on the page cache.

$(document).on("change","#customerpurchaseitems-1-product_name", function (e) { var PricesId = +parseFloat(this.value); $.get('index.php?r=juliuscrmp/products/get-prices', {PricesId: PricesId}, function (data) { var data = $.parseJSON(data) if(data !== null) { $("#customerpurchaseitems-1-product_price").prop('value', data.product_price) $("#customerpurchaseitems-1-product_quantity").prop('value',1) // $("#currency").is('value',12313131) }else { $("#customerpurchaseitems-1-product_price").prop('value', '') $("#customerpurchaseitems-1-product_quantity").prop('value','') } var a = $("#customerpurchaseitems-1-product_quantity").val(); var b = $("#customerpurchaseitems-1-product_price").val();

    $("#customerpurchaseitems-1-purchase_total").val((a*b).toFixed(2))
});

$(this).bind(e);

})

leonardojulius avatar Jun 04 '16 09:06 leonardojulius

Yes, I did something similar like above to sort this.

This is the dropdown where i was using onChange code for calling ajax function.

field($modelProduct, "[{$i}]category_id")->dropDownList($listCategory, [ 'prompt'=>'Select Category', 'class'=>'input-size', ] )->label('Category');?>
field($modelProduct, "[{$i}]product_id")->dropDownList($listProduct, ['prompt'=>'Select Product', 'class'=>'select-product-size'])->label('Product'); ?>

But since it was not working, I added the following JS function to get get id of current generated category id and then create a similar id for dependent product dropdown:

registerJs(" jQuery(function($){ $(document.body).on('change', '.input-size', function(){ var selectId = $(this).attr('id'); var selectId = selectId.replace('category', 'product'); //alert(selectId); var id1 = $(this).val(); //alert(id1); $.ajax({ type :'GET', cache : false, url : 'index.php?r=recipe/lists', data: { id : id1 }, success : function(response) { //alert(response); $('#'+selectId).html(response); } }); return false; ``` }); });"); ``` ?>

swati-clarion avatar Jun 04 '16 14:06 swati-clarion

Download my TextFile and Copy all Code and try temporary replace to see if work, Just back up your old one @Web->Assest->Folder then Press Controll F find yii2-dynamic-form.js Note not in vendor it should be at the Backend or Front end Folder or where your project save Replace all with this code*

https://github.com/wbraganca/yii2-dynamicform/files/129597/Select.2.Js.txt

leonardojulius avatar Jun 05 '16 22:06 leonardojulius

i have the same issue, this is my _form `

= $form->field($modelResolucion, "[{$i}]cat_dannos_id")->widget(Select2::classname(), [ 'data' => ArrayHelper::map(\app\models\Ncategoriadannos::find()->asArray()->all(), 'id_categoriadannos', 'categoriadannos_desc'), 'options' => ['placeholder' => 'Seleccione una categoría', 'onchange'=>' $.get( "'.Url::toRoute('/resolucion/lists').'", { id: $(this).val() } ) .done(function( data ) { $( "#'.Html::getInputId($modelResolucion, "[{$i}]conceptos_dannos_id").'" ).html( data ); } ); '], 'pluginOptions' => [ 'allowClear' => true, 'width' => '250px' ], ]); ?>
                        </div>
                        <div class="col-sm-6">
                            <?= $form->field($modelResolucion, "[{$i}]valor")->textInput(['maxlength' => true]) ?>
                        </div>

`

this is my controller ` public function actionLists($id) { $rows = \app\models\Entidad::find()->where(['orga_fk' => $id])->all();

    echo "<option>Selecione una entidad</option>";

    if(count($rows)>0){
        foreach($rows as $row){
            echo "<option value='$row->id_entidad'>$row->entidad_nombre</option>";
        }
    }
    else{
        echo "<option>No existe ninguna entidad</option>";
    } 
}

`

epulgaron avatar Jun 27 '16 19:06 epulgaron

i have the same issue....

My function only works with the first item.

`$(function() { $('#materialcopiasitens-{$i}-item_qtoriginais').keyup(function() {
updateTotal(); });

$('#materialcopiasitens-{$i}-item_qtexemplares').keyup(function() {  
    updateTotal();
});

$('#materialcopiasitens-{$i}-item_mono').keyup(function() {  
    updateTotal();
});

$('#materialcopiasitens-{$i}-item_color').keyup(function() {  
    updateTotal();
});

var updateTotal = function () {
  var item_qtoriginais  = parseInt($('#materialcopiasitens-{$i}-item_qtoriginais').val());
  var item_qtexemplares = parseInt($('#materialcopiasitens-{$i}-item_qtexemplares').val());
  var item_mono         = parseInt($('#materialcopiasitens-{$i}-item_mono').val());
  var item_color        = parseInt($('#materialcopiasitens-{$i}-item_color').val());

  var item_qteCopias = item_qtoriginais * item_qtexemplares;
  var item_qteTotal  = (item_mono + item_color) * item_qtexemplares ;

  var mono = 0.1;
  var color = 0.6;

  var item_totalValorMono = (item_qtexemplares * item_mono) * mono;
  var item_totalValorColor = (item_qtexemplares * item_color) * color;
  var item_totalGeral = item_totalValorMono + item_totalValorColor;



if (isNaN(item_qteCopias) || item_qteCopias < 0) {
    item_qteCopias = '';
}

if (isNaN(item_qteTotal) || item_qteTotal < 0) {
    item_qteTotal = '';
}

if (isNaN(item_totalValorMono) || item_totalValorMono < 0) {
    item_totalValorMono = '';
}

if (isNaN(item_totalValorColor) || item_totalValorColor < 0) {
    item_totalValorColor = '';
}
  $('#materialcopiasitens-{$i}-item_qtecopias').val(item_qteCopias);
  $('#materialcopiasitens-{$i}-item_qtetotal').val(item_qteTotal);

  $('#materialcopiasitens-{$i}-item_totalvalormono').val(item_totalValorMono);
  $('#materialcopiasitens-{$i}-item_totalvalorcolor').val(item_totalValorColor);
  $('#materialcopiasitens-{$i}-item_totalgeral').val(item_totalGeral);
};

});`

FernandoMauricio avatar Aug 10 '16 21:08 FernandoMauricio

@FernandoMauricio have you got the solution for your issue, I am facing the same issue.

Nayank9 avatar Aug 20 '16 06:08 Nayank9

@swati-clarion @epulgaron @FernandoMauricio You need to call your jquery script after each dynamicform_wrapper call following way :

jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) { jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) { jQuery(this).html("Installment: " + (index + 1)) // ADD YOUR JQUERY SCRIPT HEAR. }); });

karmrajzala avatar Aug 23 '16 05:08 karmrajzala

i have the same issue.

My function only works with the first item......

= Html::activeDropDownList($modelsstuinfo,"[{$index}]Board_Id", ArrayHelper::map(Seed::findAll(array('System_Code_Type'=>'Education_Board')), 'System_Code_Id', 'System_Code_Description'), ['prompt'=>'--Select Board--', ``` 'class'=>'form-control', 'Onchange'=>'$.get("loadboardid?ind='.$index.'&id='.'"+$(this).val(),function(ind,data){ $("#'.Html::getInputId($modelsstuinfo, '['.$index.']divboardid').'" ).html(ind,data); });' ]);?>

debosreebiswas avatar Aug 24 '16 07:08 debosreebiswas

I solve my problem ... just Add

registerJs(" jQuery(function($){ $(document.body).on('change', '.input-size', function(){ var selectId = $(this).attr('id'); var selectId = selectId.replace('category', 'product'); //alert(selectId); var id1 = $(this).val(); //alert(id1); $.ajax({ type :'GET', cache : false, url : 'index.php?r=recipe/lists', data: { id : id1 }, success : function(response) { //alert(response); $('#'+selectId).html(response); } }); return false; ``` }); ``` });"); ?>

under the dropdown

debosreebiswas avatar Aug 24 '16 09:08 debosreebiswas

21752918_273427329814490_914615388048413344_o i have problem with input append

Njcreation avatar Sep 19 '17 09:09 Njcreation

Download my TextFile and Copy all Code and try temporary replace to see if work, Just back up your old one @Web->Assest->Folder then Press Controll F find yii2-dynamic-form.js Note not in vendor it should be at the Backend or Front end Folder or where your project save Replace all with this code*

https://github.com/wbraganca/yii2-dynamicform/files/129597/Select.2.Js.txt

not working :(

kevinnhendy avatar Apr 05 '20 13:04 kevinnhendy

What I have done is to use a parent element which exists on DOM load. like this. So if anything changes inside it, it triggers.

$(document).on('change input', '#parent-element-id', function() { alert("changed"); });

pckrishnadas88 avatar Jul 01 '20 02:07 pckrishnadas88