29

What is difference between $("#id").val.length and $("#id").val().length?

When I write $("#id").val.length then the output is 1 and $("#id").val().length then the output is the length of the written characters.

What is the explanation?

2

3 Answers 3

60

$("#id").val returns the function definition of val and length of a function is the number of parameters the function is expecting as the val takes one parameter(setter to set the value) the length is 1, whereas val() will invoke the function and get the returned value and length on it will return the number of characters in the value.

The correct use is $(selector).val().length

I will also recommend to use VanillaJS's trim or jQuery's $.trim on val() before checking length to remove leading and trailing spaces.

Sign up to request clarification or add additional context in comments.

1 Comment

length of a function is the number of parameters the function is expecting Very nice! Did not know that. (and yes, have tested it). Try (function test(one, two){}).length
9

Let us have a look at both the code:

Case 1:

$("#id").val.length 

Here .val return the method definition for .val(). and .length along with it returns number of maximum argument methods accepts(for example 2 for .toggleClass())

Case 2:

$("#id").val().length 

Here .val() returns the method evaluation result i.e. value of DOM object in string format and .length returns the length string value returned.

Correct way:

Case 2 is the correct way of using .val() along with length as it returns length of value of element associated to it.

1 Comment

As count of number of method is 1, .length along with it returns 1. this isn't correct. The count of the number of parameters of the method is 1.
1

With $("#id").val you get the function (the source code) and with $("#id").val() this function will be called and executed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.