Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Checking array with users input after a click

After the user clicks enter I want the users input to check a list of zipcodes to match if they are valid or not.

What I have so far... Not 100% sure what I'm doing wrong, but it keeps showing the wrong console log (else statement) even when entering the correct zip

 $(".checking_zips").click(function() {
  var input_zip = document.getElementById("zip_input").value; 
  var zipcodes = [0001, 0002, 
                  0003, 0004, 
];

  if (zipcodes.indexOf(input_zip) > -1){
    console.log("it works correctly")
  }

     else{
    console.log("it still works")

  }
  }); 
<div class="form helper">
<div class="zip_input">
<input type="text" v-model="zip" 
maxlength="5" id="zip_input" placeholder="ex:94301"/>
</div>  
<button class="checking_zips">Enter</button>
</div>

1 Answer

The issue is that input_zip is a string, while zipcodes contains integers. Strings and integers are not treated as the same thing, even if the string consists of nothing but integers.

If you convert input_zip to an integer using parseInt like this:

$(".checking_zips").click(function() {
  var input_zip = parseInt(document.getElementById("zip_input").value)
  var zipcodes = [0001, 0002, 
                  0003, 0004, 
  ];

  if (zipcodes.indexOf(input_zip) > -1) {
    console.log("it works correctly")
  }
  else {
    console.log("it still works")
  }

}); 

Then your code will work.

YO, thanks man!