Yii2:动态获取字段的 ID


Yii2: Getting Id of a field dynamically

我正在使用以下代码从另一个表中自动填充数据,效果很好。

<?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'...

use ''

yii''helpers''Html::getInputId($model, 'attribute').

getInputId() 公共静态方法

为指定的属性名称或表达式生成适当的输入 ID。

此方法将结果 getInputName() 转换为有效的输入 ID。例如,如果 getInputName() 返回 Post[content],则此方法将返回 post-content。

public static string|array getInputId ( $model, $attribute )

例:

<?= Html::getInputId($model, 'attribute') ?>

动态地:

<?= Html::getInputId($model, '['.$index.']attribute') ?>