/    Sign up×
Community /Pin to ProfileBookmark

Unintended Div Build-Up

How do I keep the red divs from building up (one under another) with each onclick event? I tested variations of removeChild(div) without success. Is removeChild(div) part of the answer and I’m just using it wrong or is there a better approach?

My script:

[code=html]<html>
<head>
<script type=”text/javascript”>
function showHint(str) {
if (str.length==0) {
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var div = document.createElement(‘div’);
div.setAttribute(‘id’, ‘link_container’);
div.setAttribute(“style”,”background-color:red;”);
//div.style.backgroundColor = ‘red’;
div.style.width = ‘300px’;
div.style.height = ‘100px’;
div.style.margin = ‘-15px 0px 0px 75px’;
var txt=xmlhttp.responseText;
var strA = txt.slice(0,txt.indexOf(“,”)); //define number of cycles of For Loop
var str = txt.substr(txt.indexOf(“,”)+1); //cut 1st position from string and save remaining info
for (i=0; i<=strA; i++){
var newLink = document.createElement(‘a’); //create anchor
var linkName = str.slice(0,str.indexOf(” ,”)+1);
var linkName = linkName.split(‘ ‘).join(”);
newLink.href = “http://localhost/” + linkName+”.php”;
newLink.innerHTML = linkName;
var str = str.substr(str.indexOf(“,”)+1);
div.appendChild(newLink);
var newBr = document.createElement(‘br’); //create break
div.appendChild(newBr);
}
//document.getElementsByTagName(‘body’)[0].removeChild(div);
document.getElementsByTagName(‘body’)[0].appendChild(div);
}
}
xmlhttp.open(“GET”,”gethint.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type=”text” onkeyup=”showHint(this.value)” size=”20″ />
</form>

</body>
</html>[/code]

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @niche1 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...