javascript – How to write java script script from PHP code-ThrowExceptions

Exception or error:

I’m trying to process the code here.
I’m talking about this code:

    <html>
 <label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>   
     <script>   
    function checkLength(object, maxlength, label) {
        charsleft = (maxlength - object.value.length);

        // never allow to exceed the specified limit
        if( charsleft < 0 ) {
    object.value = object.value.substring(0, maxlength-1);
        }

        // set the value of charsleft into the label
        document.getElementById(label).innerHTML = charsleft;
    }  
    </script>
        </html>

The code works fine based on html.

I am very interested to know why when I send it via PHP there is no comment?

Is it possible to get this code to work from PHP?

   <html>
   <head>
       <meta charset="utf-8" />
       <title></title>
    </head>
    <body>
        <?php     
    echo '<label id="LblTextCount"></label>';
    echo '<textarea name="text" onKeyPress="checkLength(this, 512, "LblTextCount")">';
   echo "</textarea>";


    echo "      <script>";
    echo "function checkLength(object, maxlength, label) {";
    echo "    charsleft = (maxlength - object.value.length);";

        // never allow to exceed the specified limit
    echo "    if( charsleft < 0 ) {";
    echo "        object.value = object.value.substring(0, maxlength-1);}";
        // set the value of charsleft into the label
     echo " document.getElementById(label).innerHTML = charsleft;}";

    echo"    </script>";
    echo "<br>";
    ?>
How to solve:

The output of your php code is wrong formatted javascript and html, and has some syntax error in it. To easily achieve the same thing try the code below

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

<?php
echo <<<HTML
<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>   

<script>   
function checkLength(object, maxlength, label) {
    charsleft = (maxlength - object.value.length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        object.value = object.value.substring(0, maxlength-1);
    }

    // set the value of charsleft into the label
    document.getElementById(label).innerHTML = charsleft;
}  
</script>
HTML;
?>

    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *