如何使用JavaScript获取文本字段的值? (jQuery的) [英] How to get value of a text field using JavaScript? (jQuery)

查看:137
本文介绍了如何使用JavaScript获取文本字段的值? (jQuery的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery获取文本字段的值,但是它不起作用.

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

下面是测试:

我在HTML中有这个

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

在JavaScript中,使用jQuery (这不起作用):

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

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

在JavaScript中,不使用jQuery (可行):

In JavaScript, not using jQuery (this works):

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

为什么jQuery返回未定义"?

Why is jQuery returning 'undefined' ?

推荐答案

jQuery将原始DOM对象包装在其自己的对象中,因此不能直接访问.value属性.

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

要获取原始DOM对象,可以将jQuery对象作为数组访问:

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

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

或者,jQuery提供了一种获取输入值的方法:

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

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

这篇关于如何使用JavaScript获取文本字段的值? (jQuery的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆