0

I have written a function that calls a zipcode API to retrieve the address when entering a ZIP code. (Note: it's a Dutch application and a Dutch zipcode consists of 4 numbers and 2 letters.)

This is the function:

function zipcodeApiCall(zipcodeNum, zipcodeAlfa)
{
    console.log(zipcodeNum);
    if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
    {
        //some code to call the API that returns some data
    }
}

//Call the function
var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
var result = zipcodeApiCall(zipcodeNum, 'KK');

The problem is that I get the error that zipcodeNum is undefined when retrieving its length. The output of:

console.log(zipcodeNum);

for zipcode numbers 1312 is two lines:

1312
undefined

Which gives me the error 'Uncaught TypeError: Cannot read property 'length' of undefined'. Why does this happen?

What's also strange is that when I retrieve the value of zipcodeNum inside the function, like so:

function zipcodeApiCall()
{
    var zipcodeNum = $("#zipcodeNum").val(); //Retrieve val from input field
    var zipcodeAlfa = 'KK';
    console.log(zipcodeNum);
    if(zipcodeNum.length == 4 && zipcodeAlfa.length == 2)
    {
        //some code to call the API that returns some data
    }
}
var result = zipcodeApiCall();

the code executes fine and I don't get any errors.

royhoey
  • 1
  • 2
  • 1
    Where is the actual invocation of the function? It sounds like undefined is actually being passed through. A codepen/plunkr etc. would be useful. – mattdotdev Apr 14 '16 at 15:08
  • Show us where you call `zipcodeApiCall`. – Bergi Apr 14 '16 at 15:35
  • Sorry I forgot to add that line, I've edited my code now – royhoey Apr 14 '16 at 16:59
  • 1
    where's the second console.log line coming from? You've only shown one in your code. – Alnitak Apr 14 '16 at 17:01
  • So `$("#zipcodeNum").val()` is yielding `undefined`? Sounds like a duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/q/14028959/1048572) then – Bergi Apr 14 '16 at 17:04

0 Answers0