我使用yii2動態窗體wbraganca和動態形式我使用kartik/select2。這是我的視圖代碼:yii2 dropDownList當從所有索引總是得到值總是晚一步
<div class="col-sm-8 col-md-3">
<?= $form->field($detail, "[{$i}]item_id")->widget(Select2::className(), [
'data' => ArrayHelper::map(Item::find()->all(), 'id', 'name'),
'language' => 'en',
'options' => ['placeholder' => 'Select a item ...', 'onchange' => 'getItemPrice($(this))'],
'pluginOptions' => [
'allowClear' => true,
],
]);
?>
</div>
<div class="col-sm-4 col-md-2">
<?= $form->field($detail, "[{$i}]qty")->widget(MaskedInput::className(),
[
'clientOptions' => [
'alias' => 'numeric',
'groupSeparator' => ',',
'digits' => 0,
'autoGroup' => true,
'removeMaskOnSubmit' => true,
'rightAlign' => false,
],
'options' => [
'class' => 'form-control',
'onchange' => 'calculateSubtotal($(this))',
]
]) ?>
</div>
<div class="col-sm-4 col-md-2">
<?= $form->field($detail, "[{$i}]price")->widget(MaskedInput::className(),
[
'clientOptions' => [
'alias' => 'numeric',
'groupSeparator' => ',',
'digits' => 0,
'autoGroup' => true,
'removeMaskOnSubmit' => true,
'rightAlign' => false,
],
'options' => [
'class' => 'form-control',
'onchange' => 'calculateSubtotal($(this))',
]
]) ?>
</div>
<div class="col-sm-4 col-md-2">
<?= $form->field($detail, "[{$i}]total")->widget(MaskedInput::className(),
[
'clientOptions' => [
'alias' => 'numeric',
'groupSeparator' => ',',
'digits' => 0,
'autoGroup' => true,
'removeMaskOnSubmit' => true,
'rightAlign' => false,
]
]) ?>
</div>
,這是我的JavaScript代碼
function getItemPrice(item){
var index = item.attr("id").replace(/[^0-9.]/g, "");
var item_id = $('#purchaseorderdetail-'+ index + "-item_id").val();
$.get('../item/get-price', {id : item_id}, function(data){
$('#purchaseorderdetail-' + index + '-price').val(data);
$('#purchaseorderdetail-' + index + '-qty').val(1);
$('#purchaseorderdetail-' + index + '-total').val(data);
});
calculateTotal(Number(index)+1);
}
function calculateSubtotal(item){
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qty = $('#purchaseorderdetail-' + index + '-qty').val();
qty = qty == "" ? 0 : Number(qty.split(",").join(""));
var price = $('#purchaseorderdetail-' + index + '-price').val();
price = price == "" ? 0 : Number(price.split(",").join(""));
$('#purchaseorderdetail-' + index + '-total').val(qty * price);
calculateTotal(Number(index)+1);
}
function calculateTotal(index){
var total = 0;
for(i=0; i< index; i++){
var subtotal = $('#purchaseorderdetail-' + i + '-total').val();
subtotal = subtotal == "" ? 0 : Number(subtotal.split(",").join(""));
alert(subtotal);
total = total + subtotal;
}
$('#purchaseorder-total').val(total);
}
當我選擇第一項(價格150000和qty 1),函數計算總總是給出結果0,然後我添加第二個項目(價格爲370,000和1),結果總數= 150,000。當我將第二件物品換成價格爲55,000的另一件物品時,總計520,000件。
我錯過了什麼?請指教。 謝謝