JavaScript 如何获取文本输入字段的值
我们可以使用JavaScript的各种方法来获取文本输入字段的值。有一个 文本值属性 可以 设置 和 返回 文本字段的值属性的值。此外,我们还可以在脚本中使用 jQuery的val()方法 来 获取 或 设置 文本输入字段的值。
以下是获取或设置文本输入字段值的两种不同方法:
使用文本值属性: 文本值属性用于设置或返回输入字段的值属性的值。值属性指定输入文本字段的初始值,其中包含了默认值或用户输入的值。
语法:
Get value : textObject.value
Set value : textObject.value = text
示例1: 这个示例使用Text value属性从输入文本字段中获取值。
GeeksforGeeks
Text value property
Change the text of the text field,
and then click the button below.
Name:
// Here the value is stored in new variable x
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
输出:
使用jquery的val()方法:val()方法 用于 返回 或 设置 所选元素的value属性的值。在默认模式下,在第一个匹配的元素上返回value属性的值,并在所有匹配的元素上设置value属性的值。
语法:
Get value : (selector).val()
Set value :(selector).val(value)
示例2: 该示例描述了使用jquery val() 方法来获取输入字段的值。
(document).ready(function() {
("button").click(function() {
// Here the value is stored in variable.
var x = $("input:text").val();
document.getElementById("demo").innerHTML = x;
});
});
GeeksforGeeks
jquery val() method
Change the text of the text field, and
then click the button below.
Name:
value="GeeksforGeeks">
输出: