从 Yii2 表单字段调用 JavaScript 函数

Call JavaScript Function from Yii2 Form Field

我正在尝试创建一个 JS 函数来在 Yii2 中实时计算 textarea 字符数。在正常 HTML 中,以下代码工作正常:

<textarea id="text" onkeyup="count();" placeholder="Enter Some Text"></textarea>

但是,将此代码映射到 Yii2 表单元素给我带来了问题。这是我尝试过的方法,但未检测到函数 count():

<?= $form->field($model, 'message')->textarea(['placeholder' => '1 message = 160 characters','rows' => 6, 'onkeyup' => 'count();']) ?>

我做错了什么吗?以下是我的完整表单代码:

<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\datecontrol\DateControl;

/**
 * @var yii\web\View $this
 * @var app\models\Messages $model
 * @var yii\widgets\ActiveForm $form
 */

/* start getting the totalamount */
$script = <<<EOD
    function count()
    {
      var total = document.getElementById("messages-message").value;
      total = total.replace(/\s/g, '');
      document.getElementById("total").innerHTML="Total Characters:"+total.length;
    }
EOD;

$this->registerJs($script);
?>

<div class="messages-form">
    <?php 
        $form = ActiveForm::begin([
            'id' => 'messages-form-vertical', 
            'type' => ActiveForm::TYPE_VERTICAL
        ]); 
    ?>

    <?= $form->field($model, 'type')->textInput(['placeholder' => 'Enter Type...']) ?>

    <?= $form->field($model, 'senderID')->textInput(['placeholder' => 'Enter Sender ID...', 'maxlength' => 15]) ?>

    <?= $form->field($model, 'recepient_mobile')->textInput(['placeholder' => 'Enter Recepient Mobile...', 'maxlength' => 15]) ?>

    <?= $form->field($model, 'characters')->textInput(['placeholder' => 'Enter Characters...']) ?>

    <?= $form->field($model, 'status')->textInput(['placeholder' => 'Enter Status...', 'maxlength' => 50]) ?>

    <?= $form->field($model, 'sms_count')->textInput() ?>

    <?= $form->field($model, 'message')->textarea(['placeholder' => '1 message = 160 characters','rows' => 6, 'onkeyup' => 'count();']) ?>

    <p id="total">Total Characters:0</p>

    <div class="form-group">
        <?php echo Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
            ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
        ); ?>
    </div>

    <?php ActiveForm::end(); ?>
</div>

感谢您的帮助。

你应该使用:

$this->registerJs($script, View::POS_HEAD);

默认 registerJs() uses POS_READY$position。这意味着 JavaScript 将包含在 jQuery(document).ready() 中,因此定义的函数在全局上下文中不可用。