Solution 1 :

Ok,so you do this by using

var value = $("#field").val();

The reason the first approach works is because it returns the HTML element object and you assess its value property.(you can access any property of that element using . operator)

However using jquery returns JQUERY object and since it does not have a value property u can not access it. You need to use jqueries val function.

Solution 2 :

In jquery you use the method val(). It would look like this :

var value2 = $('#field').val();

Problem :


I’m new to web development and tring to understand some basics. To make it short, I have an input like this:

<input type="text" id="field" name="field" placeholder="Write something here...">

On separate file with JS extension I want to get the value from this input. I tried doing so in two ways, one in vanilla JS:

var value = document.getElementById('field').value;

This returns the correct value, and second with jQuery:

var value2 = $('#field').value;

And getting an ‘undefined” from the second.

Why is this so?


Comment posted by mcgtrt

Lol, ofc I have it, and it’s the first script loaded

Comment posted by

jQuery 101, read documentation

Comment posted by mcgtrt

All right, this one works! But why just normal

Comment posted by shim-kun

It’s because the $ selector will return an jquery object instead of a html element