0

I have this simple script that counts how many array elements matches my input but it seems like every if statement returns false.

I have checked that both (array element and input value) are Strings. Just can't figure out why it returns false.

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">
      </div>
      <p id="count"></p>

      <script type="text/javascript">

      var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
      var n = 0;

      for (var i = 0; i < bloodTypes.length; i++) {
         if (bloodTypes[i] == document.getElementById("searchType").value){
            n++;
         }
      }
      document.getElementById("count").innerHTML = n;
      </script>
   </body>
</html>
6
  • 1
    We need to see your corresponding HTML as well. Also, you don't have this code inside of a function and therefore nothing is ever "returned" from it. Commented Nov 25, 2018 at 20:41
  • Not sure why you would expect more than one match in an array of unique values if using equality match. Provide a minimal reproducible example that includes input values yo u used Commented Nov 25, 2018 at 20:43
  • the for statement loops through every element and checks if that element is equal to the input value. And if it is then it increments the variable n by 1 and continues. So for example if my input value would be "AB+" then variable n should be 5 but it's 0 Commented Nov 25, 2018 at 20:46
  • Yes, we can see that. But, please show us the corresponding HTML as well. And, let us know where you've placed your script within the document. Commented Nov 25, 2018 at 20:46
  • 1
    It doesn't work for simple reason you only check when page loads before any user input Commented Nov 25, 2018 at 20:55

3 Answers 3

1
var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
var searchInput = document.getElementById("searchType");
var countElement = document.getElementById("count");

searchInput.addEventListener('input', function (e) {
    var n = 0;
    for (var i = 0; i < bloodTypes.length; i++) {
        if (bloodTypes[i] == e.target.value) {
            n++;
        }
    }
    countElement.textContent = n;
});
Sign up to request clarification or add additional context in comments.

1 Comment

ah, yeah. it should listen the event.
0

You have three issues.

  1. Your code is running immediately as soon as the page loads, which is before the user has a chance to input a search string.
  2. Your count code must be bound up into a callable unit of code (a function) so it can be run as a unit at the right time.
  3. You have to have a "trigger" (event) for the count code. In the example below that's the change event, which occurs after the value of the input has changed and the focus on the control is lost (just hit TAB after typing an input value).

See the comments inline below for more detail:

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">(hit TAB after entering data)
      </div>
      <p id="count"></p>

      <script type="text/javascript">
      
      // Your old code was testing for matches before the user had a chance to
      // input anything. You need to set up an "event handler" that will call
      // your code at the right time:
      document.getElementById("searchType").addEventListener("change", count);

      // You must gather up all this code into a function that can be called 
      // after there has been some search input
      function count(){
        var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
        var n = 0;

        for (var i = 0; i < bloodTypes.length; i++) {
         if (bloodTypes[i] == document.getElementById("searchType").value){
            n++;
         }
        }
        
        // Only use .innerHTML when the string you are working with contains HTML
        // that needs to be parsed. When it's not HTML, use .textContent.
        document.getElementById("count").textContent = n;
      }
      </script>
   </body>
</html>

Now that we've got it working, this can be done in a simpler way using the Array.forEach() method and the JavaScript ternary operator.

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">(hit TAB after entering data)
      </div>
      <p id="count"></p>

      <script>
      // Get references to DOM elements just once:
      let input = document.getElementById("searchType");
      let output = document.getElementById("count");
      
      input.addEventListener("change", count);

      function count(){
        var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
        var n = 0;

        bloodTypes.forEach(function(type) {
         // Always call .trim on input strings. It strips off leading and 
         // trailing spaces that the user might have inadvertently added.
         // The following uses the JavaScript "ternary" operator, which is a 
         // way to write a simple if/then/else statement. It works like this:
         // condition ? true value : false value
         n = (type == input.value.trim()) ? n + 1 : n;
        });
        
        output.textContent = n;
      }
      </script>
   </body>
</html>

3 Comments

Thanks for your help, I facepalmed myself when I saw your first point (running immediately) got the code working now. Shouldn't code when it's late at night. Thank you!
@JensAitola You're welcome. Take a look at my updated answer for a second, more streamlined approach.
That updated one looks much better I'm going with that one!
0

You need to have that script run after the input text box has been filled out. For example, if you add a "search" button, and add a click handler for it, you could execute your code in the 'click' event listener for the search button.

If you run the code snippet below and enter AB+ into the box and then click the search button, you'll get 5, as expected:

<div>
  <input type="text" id="searchType">
  <button id="search">Search</button>
</div>
<p id="count"></p>

<script type="text/javascript">

document.getElementById('search').addEventListener('click', () => {
  var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
  var n = 0;

  for (var i = 0; i < bloodTypes.length; i++) {
     if (bloodTypes[i] == document.getElementById("searchType").value){
        n++;
     }
  }
  document.getElementById("count").innerHTML = n;
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.