Reputation: 59
I'm not sure if the title makes sense, but I'm trying to dynamically change the value of a variable in a loop through a text input.
Take a look at my code so far
<script type="text/javascript">
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
for(count = 0; count < 5; count++, str += plus){
document.write("<br />");
document.write(str);
}
};
</script>
<input type="text" id="inputter" name="inputter"></form>
<button id="sub" type="button" onclick="test()">Try It Out</button>
so if you hit the button with whatever you put in as a value in the text field, say for example... You put "X" the result would be...
X
XX
XXX
XXXX
XXXXX
but then the form field disappears and I would have to refresh the page to do it again? Is there a way I can do this dynamically? So without refreshing, I would like to be able to type in a new string, and it would change.
Thanks in advance!
Upvotes: 2
Views: 830
Reputation: 2964
use a div and fill with data:
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form>
<input type="text" id="inputter" name="inputter">
<button id="sub" type="button" onclick="test()">Try It Out</button>
</form>
<div id="theText"></div>
<script type="text/javascript">
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
var theText = document.getElementById('theText');
for (count = 0; count < 5; count++) {
str += plus;
theText.innerHTML = theText.innerHTML + str + '<br/>';
}
};
</script>
</body>
</html>
Upvotes: 1
Reputation: 780909
document.write()
is overwriting your page. Don't use it, use DOM modification functions to put the string in a DIV.
<input type="text" id="inputter" name="inputter"></form>
<button id="sub" type="button" onclick="test()">Try It Out</button>
<div id="output"></div>
<script>
function test() {
var count;
var str = document.getElementById('inputter').value;
var plus = str;
var output = '';
for(count = 0; count < 5; count++, str += plus) {
output += "<br />" + str;
}
document.getElementById('output').innerHTML = output;
};
</script>
Upvotes: 1
Reputation: 1398
Do you mean something like this?:
var str;
function test() {
var str += document.getElementById('inputter').value;
document.write("<br />");
document.write(str);
}
Upvotes: 0