我正在使用下面的代码自动填充另一个表中的数据,效果很好。
<?php
$this->registerJs("$('#otinstrumententry-0-instrument_name').on('change',function(){
$.ajax({
url: '".yii\helpers\Url::toRoute("ot-note/instrument")."',
dataType: 'json',
method: 'GET',
data: {id: $(this).val(),
},
success: function (data, textStatus, jqXHR) {
$('#otinstrumententry-0-instrument_code').val(data.instrument_code);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});");
?>
我现在面临的问题是我添加重复字段,其中 id 是动态生成的,因此我上面的解决方案仅适用于第一行,而对于连续行,字段的 id 会发生更改,例如
#otinstrumententry-1-instrument_name
和 #otinstrumententry-2-instrument_name
还
#otinstrumententry-1-instrument_code
和 #otinstrumententry-2-instrument_code
我该如何解决这个问题。
我添加行的代码如下:
<div id="instrument_entry">
<h3>Instruments Used</h3>
<?php $id = 0; ?>
<?php foreach ($otinstrumentModels as $otinstrument) { ?>
<div id="language" class="work-data-pad brdr-work marbtm10 row">
<div class="col-md-4">
<?= $form->field($otinstument, '[' . $id . ']' . 'instrument_name')->DropDownList(ArrayHelper::map(\app\models\Instrument::find()->all(), 'id', 'instrument_name' ),
[ 'prompt' => 'Please Select' ])?>
</div>
<div class="col-md-2">
<?= $form->field($otinstrument, '[' . $id . ']' . 'instrument_code')->textInput(['maxlength' => 255]) ?>
</div>
<div class="col-md-1">
<?= $form->field($otinstrument, '[' . $id . ']' . 'hrs_time')->textInput(['maxlength' => 255])->label('Hrs-Time') ?>
</div>
<div class="col-md-2">
<?= $form->field($otinstrument, '[' . $id . ']' . 'total_charges')->textInput(['maxlength' => 255]) ?>
</div>
<?php ?>
<div style="margin-top: 30px;" class="col-md-3 <?php echo ($id < 1) ? 'dnone' : 'dblock'; ?>" id="divDelete" class="row-fluid">
<a class="ft11 btn-remove" onclick="deleteSection(this, 'instrument_entry');"><span class="marleft18">Remove</span></a>
</div>
</div>
<?php $id++; ?>
<?php } ?>
</div>
提前感谢您对此提出建议或任何替代解决方案。
编辑
最初,ajax 根本不会触发后续字段,但在更改代码后 -
$this->registerJs("$(document).on('change','.form-control',function(event)
现在它正在发送数据,但我仍然坚持在当前字段中填充数据,因为它仍然没有选择动态添加的字段,而是在第一行中更改了数据。
最佳答案
在所有字段中添加 css 类。和 $('.className').on('change'...
关于javascript - Yii2:动态获取字段的Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012534/