Yii2:对三个输入字段求和并将结果分配给第四个

时间:2018-03-21 10:23:37

标签: forms yii2 sum yii2-advanced-app

我有四个字段,如代码所示。我想总结night_firsthotelnight_secondhotelnight_thirdhotel并将结果分配给total_night

我该怎么做?

<?= $form->field($model, 'nights_firsthotel')->dropDownList(range(1, 10)); ?>
<?= $form->field($model, 'nights_secondhotel')->dropDownList(range(1, 10)); ?>
<?= $form->field($model, 'nights_thirdhotel')->dropDownList(range(1, 10));  ?>
<?= $form->field($model, 'total_nights')->textInput(['readOnly'=> true]) ?>

2 个答案:

答案 0 :(得分:0)

试试这个 首先,您需要为输入下拉列表设置一个ID,如果有,您可以更改我写入的ID。

第二,你需要使用JS访问它并将值相加并设置为&#34; total_nights&#34;输入

我写了代码,但我没有证明。试着告诉我

<?= $form->field($model, 'nights_firsthotel')->dropDownList(range(1, 10) ,    ['id'=>'nights_firsthotel']); ?>
<?= $form->field($model, 'nights_secondhotel')->dropDownList(range(1, 10),    ['id'=>'nights_secondhotel']); ?>
<?= $form->field($model, 'nights_thirdhotel')->dropDownList(range(1, 10),    ['id'=>'nights_thirdhotel']);  ?>
<?= $form->field($model, 'total_nights')->textInput(['readOnly'=> true,'id'=>'total_nights']) ?>

$(document).ready(function () {
    $("select").change(function () {

        var nights_firsthotel = document.getElementById("nights_firsthotel").value;
        var nights_secondhotel = document.getElementById("nights_secondhotel").value;
        var nights_thirdhotel = document.getElementById("nights_thirdhotel").value;
        var total_nights = document.getElementById("total_nights");
        total_nights.val(nights_firsthotel+nights_secondhotel+nights_thirdhotel);
    });
});

答案 1 :(得分:0)

$nights_firsthotel = Html::getInputID($model, 'nights_firsthotel');
$nights_secondhotel = Html::getInputID($model, 'nights_secondhotel');
$nights_thirdhotel = Html::getInputID($model, 'nights_thirdhotel');
$total_nights = Html::getInputID($model, 'total_nights');

$this->registerJs(<<<JS
    $(document).ready(function(){
        $("select").change(function () {
            var total_nights = 0;
            total_nights += parseInt($('#$nights_firsthotel').val()) || 0;
            total_nights += parseInt($('#$nights_secondhotel').val()) || 0;
            total_nights += parseInt($('#$nights_thirdhotel').val()) || 0;

            $('#$total_nights').val(total_nights);
        });
    });
JS
);