如何为输入框分配值?使用getElementById

时间:2018-02-22 04:01:02

标签: javascript html

如何为输入框添加值?我正在使用Firefox。

HTML

<input name="dgAgentFirstPass$ctl02$txtQuantity" id="dgAgentFirstPass_ctl02_txtQuantity" class="inputbox" onkeypress="keyInputForPhone();" style="width:50px;text-align: right" type="text">

我尝试了以下JS功能,似乎没有添加值

function CycleCount(){
        document.getElementById("dgAgentFirstPass_ctl02_txtQuantity").value = 1;
    }   

https://jsfiddle.net/x30f2rf1/8/

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var btn = document.getElementById("btn");
btn.onclick = function() {
		document.getElementById("dgAgentFirstPass_ctl02_txtQuantity").value=1;
}
&#13;
<!DOCTYPE html>
<html>
	<body>
		<input type="text" id="dgAgentFirstPass_ctl02_txtQuantity">
		<button type="button" id="btn">Button</button>
	</body>
</html>
&#13;
&#13;
&#13;

知道您的按钮ID,并在第一行的下方脚本中进行更改,即btn

var btn = document.getElementById("btn");
btn.onclick = function() {
   document.getElementById("dgAgentFirstPass_ctl02_txtQuantity").value = 1;
}

答案 1 :(得分:1)

它可以正常工作 - 你只需要等到DOM加载:

<html>
  <head>

    <script>
      function CycleCount(){
        document.getElementById("dgAgentFirstPass_ctl02_txtQuantity").value = 1;
      } 
      window.onload = function(){
        CycleCount(); 
      }
    </script>
  </head>
  <body>
    <input name="dgAgentFirstPass$ctl02$txtQuantity" type="text" id="dgAgentFirstPass_ctl02_txtQuantity" class="inputbox" onkeypress="keyInputForPhone();" style="width:50px;text-align: right" />
  </body>
</html>

答案 2 :(得分:0)

好的问题是frameset 上的index.html

的index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <title>Test Page</title>   
</head>

<frameset cols="250,*">
    <frame src="left.html" name="LEFTFRAME">
    <frame src="right.html" name="RIGHTFRAME">
</frameset>

</html>

left.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta charset="utf-8" />
    <title>Left</title>
  </head>

  <body>
    Left Frame
  </body>

</html>

right.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta charset="utf-8" />
    <title>Right</title>
  </head>

  <body>
    Right Frame
    <br>

    <input name="dgAgentFirstPass$ctl02$txtQuantity" id="dgAgentFirstPass_ctl02_txtQuantity" class="inputbox" style="width:50px;text-align: right" type="text">

  </body>

</html>

JS功能

function CycleCount(){
        document.getElementsByName("RIGHTFRAME")[0].contentWindow.document.getElementById("dgAgentFirstPass_ctl02_txtQuantity").value = 1;
    }