Jump to content

Removing Elements - Solved With Thanks


niche

Recommended Posts

I put this at the end of my code thinking that after the div displays (id = 'link_container') I can eliminate (id = 'link_container') from memory when the script ends so there's a place for another div (id = 'link_container') when/if there's onkeyup event. Wouldn't this little script remove any element with an id = 'link_container' ? <script type="text/javascript">var deleteDiv = document.getElementById('link_container');document.body.removeChild(deleteDiv);</script>

Link to comment
Share on other sites

Yes. It's after the targeted element has been created and displayed. So, I know it's there. My thought was I would delete the target with my little js. So, there's a place for it in memory in case there's another onkeyup event, but no joy. Each onkeyup event produces a new div (id = 'link_container') and the div build-up begins. Why do you think the old div isn't removing after it displays? Here the html from firebug:

<html><head><body><p><form>First name:<input type="text" size="20" onkeyup="showHint(this.value)"></form><script type="text/javascript">var deleteDiv = document.getElementById('link_container');document.body.removeChild(deleteDiv);</script><div id="link_container" style="background-color: red; width: 300px; height: 100px; margin: -15px 0px 0px 75px;"><div id="link_container" style="background-color: red; width: 300px; height: 100px; margin: -15px 0px 0px 75px;"></body></html>

Link to comment
Share on other sites

Assuming this is related to your other topic, the showHint function dynamically creates the div onkeyup. Meaning it doesn't exist when the page loads. Your script runs as soon as the browser gets to those lines (when the page is loading) so when the div is created, your script has already ran and won't run again. You need to either use my suggestion in your other topic, or move the removeChild() lines inside your showHint function, before you create the div again.

Link to comment
Share on other sites

Yes it is related. Please excuse me. I thought this topic would have better defintion. I'd like to continue here. Where would the if statement go? I've tried it several place and nogo. The if:

if (!document.getElementById('link_container')) {	var deleteDiv = document.getElementById('link_container');	document.parentNode.removeChild(deleteDiv);  }

The javascript:

<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.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].appendChild(div);   }}   xmlhttp.open("GET","gethint.php?q="+str,true);  xmlhttp.send(); }</script>

Link to comment
Share on other sites

Your code should look like this:

if (document.getElementById('link_container')) {   var deleteDiv = document.getElementById('link_container');   deleteDiv.parentNode.removeChild(deleteDiv);}

Put that code right before you create the new div.

Link to comment
Share on other sites

Every place I put it the first onkeyup event worked properly, but all subsequent onkeyup events failed to refresh the div id = 'link_container' with the updated hint (the results of the first onkeyup remained). I inserted the if statement after: xmlhttp.onreadystatechange=function() { then after: if (xmlhttp.readyState==4 && xmlhttp.status==200) { then after: function showHint(str) { Each time I saw exactly the result described above. What do you think?

Link to comment
Share on other sites

It should work if you put it right before this line:var div = document.createElement('div'); Do you get any errors in your console? Maybe post the new code you tried so we can see if anything sticks out. Make sure you're using the version JSG gave you. Ie,if (document.getElementById(...))and not the one I gave you:if (!document.getElementById(...))My version was intended to wrap your div creation code, not the removal code.

Link to comment
Share on other sites

Thanks for the offer Here's everything. This is a learning script that only works when you enter "b", "br"... etc The if:

if (document.getElementById('link_container')) {  var deleteDiv = document.getElementById('link_container');   document.parentNode.removeChild(deleteDiv);}

The html (without the if):

<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.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].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>

And the php. name it: gethint.php

<?php// Fill up array with names$a[]="Bob";$a[]="Brittany";$a[]="Brian";//$a = array('a'=>'Bob','b'=>'Brittany','c'=>'Brittany');//echo var_dump($a) . '<br/>';//get the q parameter from URL$q=$_GET["q"];//lookup all hints from array if length of q>0if (strlen($q) > 0)  {  $hint="";  for($i=0; $i<count($a); $i++)    {    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))	  {	  if ($hint=="")	    {	    $hint=$a[$i];	    }	  else	    {	    $hint=$hint." , ".$a[$i];	    }	  }    }  }// Set output to "no suggestion" if no hint were found// or to the correct valuesif ($hint == "")  {  $response="no suggestion";  }else  {  $response=$hint;  }/*$response = explode(",",$response);$response2=  "'" . "a" . "' => " . $response[0] . "'" . "b" . "' => " . $response[1];echo json_encode($response2) . '</br>';echo $hint . '</br>';;*///$hint = array();//for($i=0; $i<count($a); $i++) {//    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) {//	    $hint[] = $a[$i];//   }//}//echo json_encode($hint);//$response = "";//echo '<span onclick="document.getElementById("field2").value=this.innerHTML">Jim</span></br>';//echo "bob";//output the response//echo var_dump($response2);  //$response = "66," . $response; $response = substr_count($response," ,") . "," . $response . " ,"; echo ($response);//$var = '<span onclick="document.getElementById('field2').value=this.innerHTML">Jim</span></br>';?>

Link to comment
Share on other sites

It's still not working with:

if (xmlhttp.readyState==4 && xmlhttp.status==200) {  if (document.getElementById('link_container')) {    var deleteDiv = document.getElementById('link_container');    deleteDiv.parentNode.removeChild(deleteDiv);   }var div = document.createElement('div');...

Thoughts?

Link to comment
Share on other sites

No error or warnings on the FB console. I would have thought that there would be something about dupe IDs, but nothing. If you've tried it, did the script work for you?

Link to comment
Share on other sites

Haven't tried it until just now. Works in FF, IE, C, O, and S. When I type 'b' I get a popup with "Bob", "Brittany", "Brian". Then if I type 'r', I get a popup with just "Brittany" and "Brian". No duplicate divs, either. Maybe try clearing your browser cache?

Link to comment
Share on other sites

As I recall, last time I did that I lost the history of how I use some functions URL hinting for example. Do you have a top of mind knowledge about this?

Link to comment
Share on other sites

You can clear the cache without clearing your history. When you click Tools -> Clear Recent History you should get a popup dialog. There are a bunch of checkboxes (Browsing and Download History, Form and Search History, Cookies, Cache, etc.). Make sure that the only box checked is Cache and click Clear Now. That should delete only your browser cache (ie, downloaded images, script files, css files, etc.)

Link to comment
Share on other sites

Clearing the cache made it work. Way less painless than I remembered. Anyway, I need to thank showdowMage and justsomeguy for their help on this topic.

Link to comment
Share on other sites

No error or warnings on the FB console. I would have thought that there would be something about dupe IDs, but nothing. If you've tried it, did the script work for you?
duplicate ID's are just HTML validation errors. Javascript will work "fine" with multiple elements using the same ID, but the results will be unpredictable. It's not as if JS is scanning your markup to make sure you are following validation best practices.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...