Naeem Ali Naeem Ali - 8 months ago 61
Javascript Question

DynamicForm + javascript

I have some dynamic forms working in

Yii2
and it works fine for me, but I need to add a little function to get cost price and sale price. It is work in the first dynamic form but the other one it dose not.

My Form code :

<div class="row">
<div class="col-sm-12">
<?= $form->field($modelPoItem, "[{$i}]po_item_no")->dropDownList(
arrayhelper::map(Itemes::find()->all(),'itemes_id','item_name'),
['prompt'=>'select Item', 'onchange' => 'getProduct($(this))', 'onkeyup' => 'getProduct($(this))']
) ?>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => 128 ]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelPoItem, "[{$i}]cost_price")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelPoItem, "[{$i}]sale_price")->textInput(['maxlength' => 128]) ?>
</div>
</div>


And here is my JS code :

function getProduct(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var itemes_id =$('#poitem-'+index+'-po_item_no').val();
$.get('index.php?r=itemes/price',{ itemes_id : itemes_id },function(data)
{
var data=$.parseJSON(data);
alert('#poitem-'+index+'-sale_price'); // i used it just to check if the id Is correct
$('#poitem-'+index+'-sale_price').attr('value',data.sale_price);
$('#poitem-'+index+'-cost_price').attr('value',data.cost_price);
});
}


Update - 1

Update - 2

Update - 3

Answer Source

Try this:

function getProduct(item) {
   var index  = item.attr("id").replace(/[^0-9.]/g, "");
   var itemes_id =$('#poitem-'+index+'-po_item_no').val();
   $.get('index.php?r=itemes/price',{ itemes_id : itemes_id },function(data)
   {
      var data=$.parseJSON(data);

     $('#poitem-'+index+'-sale_price').val(data.sale_price);
     $('#poitem-'+index+'-cost_price').val(data.cost_price);
   });
}