Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of a text field using JavaScript? (jQuery)

Tags:

jquery

I'm trying to get the value of a text field using jQuery, but it is not working.

Below is the test:

I have this in HTML:

<input type="text" id="user_time_zone_offset_hours" name="user_time_zone_offset_hours" value="7"/>

In JavaScript, using jQuery (this does not work):

alert($('#user_time_zone_offset_hours').value); //Result is 'undefined'

In JavaScript, not using jQuery (this works):

alert(document.getElementById("user_time_zone_offset_hours").value); //Result is 7

Why is jQuery returning 'undefined' ?

like image 278
Zabba Avatar asked Dec 01 '22 09:12

Zabba


2 Answers

It doesn't work because .value isn't the correct call. Try using the .val() function.

alert($('#user_time_zone_offset_hours').val());
like image 35
JasCav Avatar answered Dec 05 '22 15:12

JasCav


jQuery wraps the original DOM objects in its own object, so the .value property isn't directly accessible.

To get the original DOM object, you can access the jQuery object as an array:

$('#user_time_zone_offset_hours')[0].value;

Alternatively, jQuery provides a method to get inputs' values:

$('#user_time_zone_offset_hours').val();
like image 66
David Tang Avatar answered Dec 05 '22 15:12

David Tang