Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between val.length and val().length in jQuery?

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?

like image 317
Mayank Vadiya Avatar asked Oct 23 '15 11:10

Mayank Vadiya


People also ask

What does val () in jQuery do?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

How can get input field length in jQuery?

We can find the length of the string by the jQuery . length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string.

What is the difference between Val and value in JavaScript?

attr('value') returns the value that was before editing input field. And . val() returns the current value.

How do you find the length of an input?

In this tutorial, we are going to learn about how to get the length of an entered text in textbox using JavaScript and jQuery. To get the length of an input textbox, first we need to use access it inside the JavaScript by using the document. getElementById() method. const textbox = document.


2 Answers

$("#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.

like image 120
Tushar Avatar answered Sep 21 '22 08:09

Tushar


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.

like image 44
Milind Anantwar Avatar answered Sep 23 '22 08:09

Milind Anantwar