JavaScript如何设置input字段的值?有时我们需要设置<input>元素的默认值, 此示例说明了这样做的方法。
文字value属性
此属性设置/返回文本字段的value属性的值。
value属性包含默认值, 用户键入的值或脚本设置的值。
语法如下:
返回value属性:
textObject.value 
 
 
设置value属性:
textObject.value = text 
 
 
属性值:
- 文本:它指定输入文本字段的值。
 - attributeValue:此参数是必需的。它指定要添加的属性的值。
 
setAttribute方法
此方法将指定的属性添加到元素, 并设置其指定的值。
如果属性已经存在, 则将设置/更改其值。
语法如下:
element.setAttribute(attributeName, attributeValue) 
 
 
参数:
- attributeName:此参数是必需的。它指定要添加的属性的名称。
 - attributeValue:此参数是必需的。它指定要添加的属性的值。
 
JavaScript设置input字段的值示例1:本示例将输入元素的值设置为" textValue"by文字值属性。
<!DOCTYPE html>
<html>
  
<head>
     <title>
         JavaScript 
       | Set the value of an input field.
     </title>
</head>
  
<body style = "text-align:center;" id = "body">
     <h1 style = "color:green;">  
             lsbin  
         </h1>
     <input type = 'text' id = 'id1' />
     <br>
     <br>
     <button onclick = "gfg_Run()">
         click to set
     </button>
     <p id = "GFG_DOWN" style="color:green; 
                             font-size: 20px;
                             font-weight: bold;">
     </p>
     <script>
         var el_down = document.getElementById("GFG_DOWN");
         var inputF = document.getElementById("id1");
  
         function gfg_Run() {
             inputF.value = "textValue";
             el_down.innerHTML = 
                    "Value = " + "'" + inputF.value + "'";
         }
     </script>
</body>
  
</html> 
 
 
输出如下:
在单击按钮之前:
 
单击按钮后:
 
示例2:本示例将输入元素的值设置为'默认值'bysetAttribute方法。
<!DOCTYPE html>
<html>
  
<head>
     <title>
         JavaScript 
       | Set the value of an input field.
     </title>
</head>
  
<body style = "text-align:center;" id = "body">
     <h1 style = "color:green;">  
             lsbin  
         </h1>
     <input type = 'text' id = 'id1' />
     <br>
     <br>
     <button onclick = "gfg_Run()">
         click to set
     </button>
     <p id = "GFG_DOWN" style="color:green; 
                             font-size: 20px;
                             font-weight: bold;">
     </p>
     <script>
         var el_down = document.getElementById("GFG_DOWN");
         var inputF = document.getElementById("id1");
  
         function gfg_Run() {
             inputF.setAttribute('value', 'defaultValue');
             el_down.innerHTML = 
                    "Value = " + "'" + inputF.value + "'";
         }
     </script>
</body>
  
</html> 
 
 
输出如下:
在单击按钮之前:
 
单击按钮后:
 
JavaScript如何设置input字段的值?以上就是关于JavaScript设置input字段的值的全部内容了。

