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

2021年3月17日14:08:49 发表评论 567 次浏览

我们可以得到的值文字输入栏在脚本中使用各种方法。有一个文本值属性可以组和返回文本字段的value属性的值。我们也可以使用jQuery val()方法内部脚本得到or组文本输入字段的值。

使用文本值属性:

语法如下:

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

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

<!DOCTYPE html>
< html >
  
< body style = "text-align:center;" >
     < h1 style = "color:green;" >  
             lsbin  
         </ 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获取文本输入字段的值?1

输入文字后, 单击:

如何使用JavaScript获取文本输入字段的值?2

使用jQuery val()方法:

val()方法

习惯于

返回

or

所选元素的value属性

。在默认模式下, 此方法返回FIRST匹配元素的value属性值, 并为所有匹配元素设置value属性值。

语法如下:

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

示例2:

<!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;" >  
             lsbin  
         </ h1 >
  
     < h2 >jquery val() method
  
</ h2 >
     < p >Name:
  
         < input type = "text"
                name = "user" 
                value = "lsbin" >
  
     </ p >
  
     < button >
       Get the value of the input field
   </ button >
  
     < p id = "demo" ></ p >
  
</ body >
  
</ html >

输出如下:

在点击按钮之前:

如何使用JavaScript获取文本输入字段的值?3

单击后, 我们得到值:

如何使用JavaScript获取文本输入字段的值?4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: