[英]How can I change this input's value when a button is clicked?
I'm trying to write a program which has several textboxes and 1 button. 我正在尝试编写一个包含多个文本框和一个按钮的程序。 When the user clicks the button the value for the textboxes changes to
how are you
. 当用户单击该按钮时,文本框的值将更改为
how are you
。
I'm not sure how to refer to the value i
for the expression document.getElementById('text'+i).value= 'how are you'
我不知道如何引用表达式
document.getElementById('text'+i).value= 'how are you'
的值i
document.getElementById('text'+i).value= 'how are you'
<input name="text1" type="text" id="text1" value="textbox 1"
onFocus="this.style.background ='yellow'" onBlur="this.style.background='white'">
<input name="text2" type="text" id="text2" value="textbox 2"
onFocus="this.style.background = 'yellow'" onBlur="this.style.background='white'">
function popup() {
for( int i; i <2, i++) {
document.getElementById('text'+i).value= 'how are you'
}
}
<input type="button" value="Click Me!" onclick="popup()"><br />
I have changed the for loop part, but its still not quite working: 我已经更改了for循环部分,但它仍然不能正常工作:
function popup() {
for( var i = 1, i <= 2, i++) {
document.getElementById('text'+i).value= 'how are you'
}
}
Would the program work with a foreach loop like in C++ ? 该程序是否可以像C ++一样使用foreach循环? First it will count the number of textboxes you have and then create a list which goes from 1 to the total number of textboxe, then write a for loop to count the textboxes.
首先,它将计算您拥有的文本框的数量,然后创建一个从1到textboxe总数的列表,然后编写for循环来计算文本框。
for(var i = 1; i <=2; i++) {
document.getElementById('text'+i).value= 'how are you'
}
Clarifications: 澄清:
i
to be 1
i
是1
i<=2
i<=2
JavaScript
is dynamic typing language, so there are no types in the variable declarations. JavaScript
是动态类型语言,因此变量声明中没有类型。
The errors you had by @esailija: 你对@esailija的错误:
i
not initialized to number. i
没有初始化为数字。 ,
instead of ;
,
代替;
int i
instead of var i
int i
而不是var i
Use the word var
to declare variables in JS. 使用单词
var
在JS中声明变量。 And don't forget your semi-colons. 不要忘记你的分号。
function popup()
{
for(var i=1; i <= 2; i++) {
document.getElementById('text'+i).value = 'how are you';
}
}
Just for simplicity, I'll point out that a for
loop that has only two iterations and one line of code inside the loop is kind of a waste of typing. 为了简单起见,我将指出
for
循环中只有两次迭代和一行代码的for
循环是一种浪费打字。 You could also just do this: 你也可以这样做:
var str = 'how are you';
document.getElementById('text1').value = str;
document.getElementById('text2').value = str;
< 2
would make it stop on 1. < 2
会让它停在1上。 As I understand you, you want the i variable to show in your text as well. 据我了解,您希望i变量也显示在您的文本中。 Just add
+ i
at the end of the string. 只需在字符串末尾添加
+ i
。 Otherwise, just remove that part. 否则,只需删除该部分。
This will loop through "text1" and "text2" 这将循环通过“text1”和“text2”
for( var i=1; i <= 2; i++) {
document.getElementById('text'+i).value = 'how are you' + i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.