Solve - val is not a function jQuery Error

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Sabina Sturzu

Solve - val is not a function jQuery Error #

The "val is not a function" jQuery error occurs when trying to call the val() function on a value that is not a jQuery object. The val() function can only be used on jQuery objects. To solve the error, you can convert the DOM element to a jQuery object, e.g. $(yourDomElement).val().

jquery val is not a function error

index.js
$(document).ready(function () { const items = $('#example input'); console.log(items); // ⛔️ ERROR: calling val() on DOM element const bad = items[0].val(); // ✅ using .value on DOM element const result1 = items[0].value; console.log(result1); // ✅ using eq() to get jQuery object const result2 = items.eq(0).val(); console.log(result2); // ✅ convert to jQuery object const result3 = $(items[0]).val(); console.log(result3); });

We used bracket notation to access the first element from an array-like object. The return value from the operation is a DOM element, not a jQuery object, therefore we can't use the val() function on it.

Here's the html for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <form id="example"> <input type="text" value="first input" /> <input type="text" value="second input" /> <input type="text" value="third input" /> </form> <!-- ✅ load jQuery ✅ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <script src="index.js"></script> </body> </html>

If you're accessing an element at specific index and want to get a jQuery object as a result, you can pass the specific index to the eq() function.

index.js
const items = $('#example input'); // ✅ using eq() const result2 = items.eq(0).val(); console.log(result2);

If you have a valid DOM element and want to get its value directly, without converting it to a jQuery object, you can use the value property instead.

index.js
const items = $('#example input'); // ✅ using .value on DOM element const result1 = items[0].value; console.log(result1);

Finally if you have a valid DOM element and want to convert it to a jQuery object and use the val() method on it, you can pass it to the jQuery(element) function.

index.js
const items = $('#example input'); // ✅ convert DOM element to jQuery object const result3 = $(items[0]).val(); console.log(result3);

The jQuery function takes a DOM element, converts it to a jQuery object and returns the result.

Use the search field on my Home Page to filter through my more than 1,000 articles.