Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.length returns undefined?

function checkInputData() {
    $('.mainSearchSubmit').live('click', function () {
        var inputData = $(this).parent().children().eq(0).val();
        console.log(inputData.length);
        //this returns undefined
        console.log(inputData);
        //and this returns text from inpu so i know there is data
    });
 }

Any ideas why is this happening, in other cases when retrieving val() from input it always comes as string??

like image 407
Davor Zubak Avatar asked Mar 06 '12 10:03

Davor Zubak


People also ask

Which property returns the length of a string?

The length property returns the length of a string. The length property of an empty string is 0.

Does .length work on a string?

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings.

Is return undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

How do you determine the length of a string?

Java String length method() The Java String class contains a length() method that returns the total number of characters a given String contains. This value includes all blanks, spaces, and other special characters. Every character in the String is counted.


1 Answers

The only explanation to length being undefined is if inputData is not a string. You neglected to mention what type of input you're working with, but in any case, casting to string should solve the issue:

function checkInputData() {
    $('.mainSearchSubmit').live('click', function () {
        var inputData = $(this).parent().children().eq(0).val();
        inputData = String(inputData); // Cast to string
        console.log(inputData.length);
        //this returns undefined
        console.log(inputData);
        //and this returns text from inpu so i know there is data
    });
 }
like image 117
Hubro Avatar answered Sep 27 '22 19:09

Hubro