JavaScript 如何获取文本输入字段的值

JavaScript 如何获取文本输入字段的值

我们可以使用JavaScript的各种方法来获取文本输入字段的值。有一个 文本值属性 可以 设置返回 文本字段的值属性的值。此外,我们还可以在脚本中使用 jQuery的val()方法获取设置 文本输入字段的值。

以下是获取或设置文本输入字段值的两种不同方法:

使用文本值属性: 文本值属性用于设置或返回输入字段的值属性的值。值属性指定输入文本字段的初始值,其中包含了默认值或用户输入的值。

语法:

Get value : textObject.value
Set value : textObject.value = text

示例1: 这个示例使用Text value属性从输入文本字段中获取值。

<!DOCTYPE html> 
<html> 
  
<body style="text-align:center;"> 
    <h1 style="color:green;">   
            GeeksforGeeks   
    </h1> 
    <h2>Text value property</h2> 
    <p> 
        Change the text of the text field,  
        and then click the button below.  
    </p> 
   
    Name:<input type="text" id="myText" value="Mickey"> 
    <button type="button" onclick="myFunction()">Try it</button> 
    <p id="demo"></p> 
  
      
    <script> 
      
    // Here the value is stored in new variable x  
    function myFunction() { 
        var x = document.getElementById("myText").value; 
        document.getElementById("demo").innerHTML = x; 
    } 
    </script> 
</body> 
  
</html>

输出:

JavaScript 如何获取文本输入字段的值

使用jquery的val()方法:val()方法 用于 返回设置 所选元素的value属性的值。在默认模式下,在第一个匹配的元素上返回value属性的值,并在所有匹配的元素上设置value属性的值。

语法:

Get value : (selector).val()
Set value :(selector).val(value)

示例2: 该示例描述了使用jquery val() 方法来获取输入字段的值。

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <script> 
    (document).ready(function() { 
        ("button").click(function() { 
              
            // Here the value is stored in variable.  
            var x = $("input:text").val(); 
            document.getElementById("demo").innerHTML = x; 
        }); 
    }); 
    </script> 
</head> 
  
<body style="text-align:center;"> 
    <h1 style="color:green;">   
            GeeksforGeeks   
        </h1> 
    <h2>jquery val() method</h2> 
    <p> 
     Change the text of the text field, and  
     then click the button below. 
    </p> 
  
    <p>Name:<input type="text" name="user" 
                   value="GeeksforGeeks"> 
     </p> 
  
    <button>Get the value of the input field</button> 
    <p id="demo"></p> 
  
</body> 
  
</html>

输出:

JavaScript 如何获取文本输入字段的值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程