简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM