mcgtrt
mcgtrt

Reputation: 787

JavaScript - Input value undefined

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?

Upvotes: 1

Views: 1682

Answers (2)

Wassaf Shahzad
Wassaf Shahzad

Reputation: 313

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.

Upvotes: 2

shim-kun
shim-kun

Reputation: 123

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

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

Upvotes: 1

Related Questions