lettter count is not repting in givinen input on javascript using -> document.elemetbyid

Viewed 31

check the error i give the input as a string and i want to output as a letter count. How many time letter is present in string?

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <script type="text/javascript">
        function my() {
            var st = document.getElementById("j").value;
            var s = "l";

            var letter_Count = 0;
            for (var position = 0; position < st.length; position++) {
                if (st.charAt(position) == s) {
                    letter_Count += 1;
                }
            }
            document.getElementById("demo").innerHTML = letter_Count;
        }
    </script>
</head>

<body>
    <p id="demo"></p>
    <input type="text" name="j" id="j" onkeyup="my()" />
</body>

</html>
1 Answers

You forgot the "" in s. This should work

function my() {
  var st = document.getElementById("j").value;
  var s = "l";

  var letter_Count = 0;
  for (var position = 0; position < st.length; position++) {
    if (st.charAt(position) == "s") {
      letter_Count += 1;
    }
  }
  document.getElementById("demo").innerHTML = letter_Count;
}
<p id="demo"></p>
<input type="text" name="j" id="j" onkeyup="my()" />

Related