javascriptyii2active-form

Call JavaScript Function from Yii2 Form Field


I am trying to create a JS function to count textarea characters in real time in Yii2. In the normal HTML, the following code works fine:

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

However, mapping this code to Yii2 form elements give me a problem. This is what I have tried and the function count() is not detected:

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

Could there be anything I am doing wrong? Below is my full form code:

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

Thank you for your help.


Solution

  • You should use:

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

    By default registerJs() uses POS_READY as $position. This means that JavaScript will be enclosed within jQuery(document).ready(), so defined functions man not be available in global context.