1

Hi

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?

3
  • Do you have jquery in your file html file? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> Commented Jun 15, 2020 at 18:04
  • Lol, ofc I have it, and it's the first script loaded Commented Jun 15, 2020 at 18:05
  • jQuery 101, read documentation api.jquery.com/val Commented Jun 15, 2020 at 18:10

2 Answers 2

2

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.

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

Comments

1

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

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

2 Comments

All right, this one works! But why just normal .value doesn't? Doesn't jQuery share the same methods than plane vanilla JS? That's something I'm trying to understand :D
It's because the $ selector will return an jquery object instead of a html element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.