Reputation: 1650
I'm trying to populate a div with a certain character which repeats itself a number of times, a pretty basic task, or so I thought, for which I wrote the following JS method:
<script>
function populateTarget()
{
var target = document.getElementById("div_target");
var nrSteps = parseInt(document.getElementById("nr").value);
for (var i=0;i<nrSteps;i++)
{
target.innerHTML+=("x");
}
}
</script>
The problem is that "x"'es appear but only for a fraction of a second which I can only notice while I have firebug on.
the function is triggered of a button in this form:
<form>
Nr de caractere: <input type="text" value="1" id="nr"/>
<br/>
Caracterul dorit:
<select id="chr">
<option value="c">c</option>
<option value="b">b</option>
<option value="g">g</option>
<option value="o">o</option>
</select>
<br/>
<button onclick="populateTarget()"> Genereaza</button>
</form>
This is the div:
<style >
body
{
color: white;
background-color: blue;
}
#div_target,#div_form
{
height: 300px;
width: 300px;
border:5px solid white;
}
#div_target
{
float: left;
overflow: scroll;
}
</style>
<div id="div_target">
</div>
No other functions mess with the inner html of the div after this, and while I know adding directly to the innerHTML is a very inelegant method I just wanted to check that I could add character before writing something more advanced.
A codepen of my code.
Does anybody have a idea on what I'm doing wrong, and maybe a solution preferably one in which I use only pure JS, no libraries?
Upvotes: 0
Views: 242
Reputation: 50807
Are you perhaps reloading the page when you fire the event that runs your populateTarget
function? Is it in a form with an action such as ".", triggered by a button, for instance?
That would explain the behavior you're seeing.
If the function ended with return false;
, it might prevent this, if my guess is right.
Upvotes: 1