在动态字段上自动填充ajax响应

时间:2015-03-13 10:25:32

标签: javascript php jquery ajax

我正在使用带有ajax请求的自动填充,这对静态字段工作正常。 例如:

$this->registerJs("$(document).delegate('.form-control','change',function(event){

    $.ajax({
        url: '".yii\helpers\Url::toRoute("ot-note/instrument1")."',
        dataType: 'json',
        method: 'GET',
        data: {id: $(this).val(),
        },
        success: function (data, textStatus, jqXHR) {
            $('#otinstrumententry-0-instrument_code').val(data.instrument_code);

            },

         beforeSend: function (xhr) {
            alert('loading!');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });
});");

我的字段是动态添加的,它不适用于动态添加的字段,代码如下: id字段变得像 #field-0-instrument_code #field-1-instrument_cdoe

除第一个字段外,Jquery无法识别连续字段,这些字段是动态添加的。

如何解决此问题。 感谢。

动态字段的

添加代码

<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($otinstrument, '[' . $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,'class'=>'form-control']) ?>      
            </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>

生成的HTML

<div id="instrument_entry">
    <h3>Instruments Used</h3>



        <div id="language" class="work-data-pad brdr-work marbtm10 row">
            <div class="col-md-4">     
            <div class="form-group field-otinstrumententry-0-instrument_name">
<label class="control-label" for="otinstrumententry-0-instrument_name">Instrument Name</label>
<select id="otinstrumententry-0-instrument_name" class="form-control" name="OtInstrumentEntry[0][instrument_name]">
<option value="">Please Select</option>
<option value="1">IMPLANTS(ORTHOPEDIC)</option>
<option value="2">O2 CHARGES PER HOUR</option>
</select>

<div class="help-block"></div>
</div>    
            </div>
            <div class="col-md-2">     
            <div class="form-group field-otinstrumententry-0-instrument_code">
<label class="control-label" for="otinstrumententry-0-instrument_code">Instrument Code</label>
<input type="text" id="otinstrumententry-0-instrument_code" class="form-control" name="OtInstrumentEntry[0][instrument_code]" maxlength="255">

<div class="help-block"></div>
</div>      
            </div>
            <div class="col-md-1">     
            <div class="form-group field-otinstrumententry-0-hrs_time">
<label class="control-label" for="otinstrumententry-0-hrs_time">Hrs-Time</label>
<input type="text" id="otinstrumententry-0-hrs_time" class="form-control" name="OtInstrumentEntry[0][hrs_time]" maxlength="255">

<div class="help-block"></div>
</div>      
            </div>
            <div class="col-md-2">     
            <div class="form-group field-otinstrumententry-0-total_charges">
<label class="control-label" for="otinstrumententry-0-total_charges">Total Charges</label>
<input type="text" id="otinstrumententry-0-total_charges" class="form-control" name="OtInstrumentEntry[0][total_charges]" maxlength="255">

<div class="help-block"></div>
</div>      
            </div>
                <div style="margin-top: 30px;" class="col-md-3 dnone" id="divDelete" class="row-fluid">           
    <a class="ft11 btn-remove" onclick="deleteSection(this, 'instrument_entry');"><span class="marleft18">Remove</span></a>               
    </div>  
</div>

    </div>

    <div class="row">
        <div class="col-md-12">
            <button type="button" class="btn btn-primary sec-btn marbtm10" onclick="addNewSection('instrument_entry', 'OtInstrumentEntry')">+ Add Instrument</button>
        </div>
    </div>

    <div class="row" style="margin-top: 20px;">
        <div class="col-md-12">
            <button type="submit" class="btn btn-success">Create</button>        </div>
    </div>

    </form> 

2 个答案:

答案 0 :(得分:0)

首先,你可以试试这个:

$this->registerJs("$(document).delegate('.form-control','change',function(event){
   sendAjax(this);
});");

function sendAjax(element)
{
    $.ajax({
        url: '".yii\helpers\Url::toRoute("ot-note/instrument1")."',
        dataType: 'json',
        method: 'GET',
        data: {id: $(element).val()},
        success: function (data, textStatus, jqXHR) {
            $('#otinstrumententry-0-instrument_code').val(data.instrument_code);

            },

         beforeSend: function (xhr) {
            alert('loading!');
         },
         error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });
}

现在您可以在新添加的元素中添加onchange="sendAjax(this)"。我认为这个解决方案可以解决您的问题。

答案 1 :(得分:0)

您的代码中只有一个硬编码值(在success处理程序中),因此我假设问题来自哪里。您可以使用.attr("id")获取当前字段ID,使用正则表达式获取数字并使用它来生成选择器:

    var currentId = $(this).attr("id");
    var generatedId = "";
    if ( currentId.match(/otinstrumententry-\d+-/) ) {
        generatedId = "#" + currentId.match(/otinstrumententry-\d+-/)[0]
                          + "instrument_code";
    }
    $.ajax({
        // ...
        success: function (data, textStatus, jqXHR) {
            if ( generatedId !== "" ) {
                $( generatedId ).val(data.instrument_code);
            }
        }
    });

另外,值得注意的是正好您想要调用哪个元素。从它的外观来看,它看起来只是select,但在不了解业务逻辑的情况下,我并不完全确定:

$(document).delegate('select.form-control','change',function(event){
});

另外,如果您使用的是jQuery 1.7或更新版本,则应将.delegate替换为其新版本.on。如果您使用的是旧版本,则应考虑更新