Reputation: 45
I am writing a code that reads a name of the person from the textbox and then shows a sign/gesture for every letter in that name. Every letter in the name is read in the FOR loop which also changes gestures/signs according to the read letter. After loop stops working the page should refresh but for some unknown reason, the page refreshes before the loop ends.
I decided to imitate this situation in a brief code illustrated below. When you will run it you will see that alert appears before the code in the loop is executed. I also created a JSFiddle for convenience HERE.
function show_name(name) {
for (var i = 0, len = name.length; i < len; i++) {
if (name[i] == "H") {
var text = document.getElementById("text_tag");
text.innerHTML = "Hillary Clinton was a hot baby in the past :D";
}
}
alert("But Bill preferred Monica :(");
}
<input type="text" id="name" size="18" style=" font-size:17px; margin-left:4px; " onchange="show_name(this.value)" />
<p id="text_tag"></p>
Upvotes: 1
Views: 102
Reputation: 892
your loop is correctly being executed. but you are getting the alert before your text appears in dom. because browsers render changes in batch so when it's finished with your show_name function it'll update the text. you can be sure by adding a console.log/alert inside your loop.
function show_name(name) {
for (var i = 0, len = name.length; i < len; i++) {
console.log(name[i]); //alert(name[i]);
if (name[i] == "H") {
var text = document.getElementById("text_tag");
text.innerHTML = "Hillary Clinton was a hot baby in the past :D";
}
}
setTimeout(function(){
alert("But Bill preferred Monica :(");
},50);
}
<input type="text" id="name" size="18" style=" font-size:17px; margin-left:4px; " onchange="show_name(this.value)" />
<p id="text_tag"></p>
Upvotes: 1
Reputation: 1039
Showing an alert doesn't mean your page is getting refreshed, also if you actually refresh your code you will lose the user data inside the input element, what your code does is search for H in the input when the data has been changed inside your loop, then show a message inside.
<p id="text_tag"></p>
alert("But Bill preferred Monica :(");
if you want the alert to be at the end of the loop then shift the position of alert() inside the loop like this.
function show_name(name) {
for (var i = 0, len = name.length; i < len; i++) {
if (name[i] == "H") {
var text = document.getElementById("text_tag");
text.innerHTML = "Hillary Clinton was a hot baby in the past :D";
}
// end of loop
if(i==(name.length-1)){
alert("But Bill preferred Monica :(");
}
}
}
PS: i tried my best to understand your question & it seems you do not really want to "refresh" the page but if you do then you should simply window.location.reload()
Upvotes: 0