Reputation: 109
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
.
I'm not sure how to refer to the value i
for the expression 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:
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++ ? 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.
Upvotes: 3
Views: 292
Reputation: 707876
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. You could also just do this:
var str = 'how are you';
document.getElementById('text1').value = str;
document.getElementById('text2').value = str;
Upvotes: 1
Reputation: 150293
for(var i = 1; i <=2; i++) {
document.getElementById('text'+i).value= 'how are you'
}
Clarifications:
i
to be 1
i<=2
JavaScript
is dynamic typing language, so there are no types in the variable declarations.
The errors you had by @esailija:
i
not initialized to number.,
instead of ;
int i
instead of var i
Upvotes: 4
Reputation: 13351
< 2
would make it stop on 1.As I understand you, you want the i variable to show in your text as well. Just add + i
at the end of the string. Otherwise, just remove that part.
This will loop through "text1" and "text2"
for( var i=1; i <= 2; i++) {
document.getElementById('text'+i).value = 'how are you' + i;
}
Upvotes: 0
Reputation: 23123
Use the word var
to declare variables in 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';
}
}
Upvotes: 1