1

I would like to create textarea character counter and limiter. I have the following codes but for some reason it doesn't work.

<?=$form->field($model, 'example', ['template' => '{label}{input}{error}', 'labelOptions' => $class_label])
          ->textarea(['onKeyDown' => 'limiter()', 'onKeyUp' => 'limiter()'])
           echo "<input id='ch' type='text' style='width:45px' readonly value ='300'> characters remain";
          ?>

Following codes are the javascript codes inserted between "...":

<script type="text/javascript">
function limiter(){
    var example = document.getElementById("example");
    if(example.value.length > 300){
        example.value = example.value.substring(0, 300);
    }
    else{
        document.getElementById("ch").value = 300 - example.value.length;
    }
} 
</script> 

I would appreciate if you could help me to correct my codes.

Thanks in advance.

  • You should provide a real [mcve]. Use the live demo feature that the stackoverflow question editor provides. Don't show irrelevent PHP. Show the generated HTML. – Quentin Oct 05 '17 at 08:38

1 Answers1

0

Having done a test, the above JavaScript works, so I can only assume it's a rendering issue of the HTML. I'm going to guess that the form input doesn't have an ID of "example". HTML should look something like the below:

<input type="text" id="example" onkeydown="limiter()" onkeyup="limiter()">
Willans
  • 143
  • 5