Have I applied the correct if statement on this character counter?

With this code Im trying to implement a character constraint counter and I want the counter to say "Over!" in red when it reaches 0, but revert to counting when the user removes characters.

This is my code so far, but it seems to me that I was using the wrong operator if

because it doesn't seem to work correctly.

<textarea id="ta" rows="1" style="width:340px;"
  onKeyDown="textCounter(this.form.ta,this.form.countDisplay);"
  onKeyUp="textCounter(this.form.ta,this.form.countDisplay);"></textarea>
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="15">
<button type="button" onclick="myFunction()">Preview</button>
<p id="go"></p>
<script>
  function myFunction() {
    var x = document.getElementById("ta").value;
    document.getElementById("go").innerHTML = x;
  }
  if (function myFunction() < 0) {
    document.getElementById("go").innerHTML = "Over!"; // tried implementing the red and the alert
  }
</script>

      

JSFiddle Demo

+3


source to share


1 answer


   function myFunction() {
       var x = document.getElementById("ta").value;
       document.getElementById("go").innerHTML = x;
       return x;
   }

      

you didn't return anything to myFunction ()

in the if statement, remove the "function" keyword:

   if (myFunction() < 0) {
       document.getElementById("go").innerHTML="Over!";

    }

      

EDIT

Hi, use this code:



Html

 <form>
<textarea id="ta" rows="1" style="width:340px;"onKeyDown="textCounter(this.form.ta,this.form.countDisplay);" onKeyUp="textCounter(this.form.ta,this.form.countDisplay);"></textarea>

<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="15">

<p id="go"></p>
</form>

      

JAVASCRIPT

var maxAmount = 15;
function textCounter(textField, showCountField) {
    if (textField.value.length > maxAmount) {
        textField.value = textField.value.substring(0, maxAmount);
    } else {
        showCountField.value = maxAmount - textField.value.length;
    }
    myFunction(showCountField.value);
}

function myFunction(value) {
    if(value<=0)
    {
        document.getElementById("go").innerHTML = "<span style='color:red'>Over!!</span>";
    }
    else
    {
       document.getElementById("go").innerHTML = value;
    }
}

      

I revised your code, removed the preview button and "Over !!" will automatically appear when the counter reaches 0.

The spell is here: http://jsfiddle.net/bh3r77pe/

+6


source







All Articles