4

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' ?

5 Answers 5

17

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();
Sign up to request clarification or add additional context in comments.

2 Comments

@Zabba, same way. If you're using the first method, put an equal sign on the right and your value after that. If you're using the second method, put your value in between the brackets, e.g. .val(1).
Yes, I just figured it out too. Thanks!
1

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

alert($('#user_time_zone_offset_hours').val());

Comments

1

Try $('#user_time_zone_offset_hours').val().

Comments

1

To get the value try

$('#user_time_zone_offset_hours').val()

you can also use

$('p').text()

to get the inner text of a paragraph element, or

$('#any_div').html()

to get HTML contents of any element.

The difference between text() and html() is that if you use text() to set HTML content, eg.

$("#and_div").text('<a href="example.com">Link</a>');

it will get escaped

&lt;a href="example.com"&gt;Link&lt;/a&gt;

Comments

0

You can use $('#user_time_zone_offset_hours').html().

Comments

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.