Javascript Erase all Nodes at once.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • NKTA
    New Member
    • Jan 2010
    • 26

    Javascript Erase all Nodes at once.

    I'm working now in a form of multiple choice and i am working with several DOM's at once. Which means i need to work with nodes and their childs.
    I was searching the web for a code that erased all nodes from a parent node when i found this link over here:
    Best way to remove child nodes
    I used and tested it, but when removing all first child nodes, i think it ends up by removing the parent itself or the first child node which doesn't me allow to create child nodes again.
    So i readapted the code again, so it sould work a little better in my case:
    Code:
    function resetAllNodes(){
    	if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
    		while (nodeChangingRadio.lastChild.hasChildNodes()) {	
                          nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);
                    }
    	}
    }

    This way, i erase all childs in a node, and still possilble add again.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    this code just don't remove anything further when you would have an 'empty' last child. so it wouldn't reliable remove all child nodes from a parent ... what the code that you linked here just claims.

    suppose the parent has some child nodes and one of them is just an 'empty' node or even a textnode ... then nothing will be removed.

    kind regards

    Comment

    • NKTA
      New Member
      • Jan 2010
      • 26

      #3
      Indeed, but its easily solved by wrapping up the textnode or empty node with a tag like <p> or <br> or if you dont want to add any kind of fomatation, the tag <span>.
      For another words:
      Code:
      // Create the textnode or empty node
      var empty = document.createElement("var that has the text/string/numbers value"); // or var empty = createTextNode(something.value);
      // and then
      var p = document.createElement("p");
      p.appendChild(empty);
      
      // Now only thing missing is appending child p to the parent node you are dealing
      // Oh yeah, there's another best use for tag, <span>, its the ideal to wrap empty nodes since well, doesn't do anything, has´'t a specific function except for CSS. When adding the tag, the text stays as it child, therefore, is erased when previous child (the tag) is also erased.
      Still lets a user re-use the parent node without erasing it.
      In the previous case (Hot linked) it kills all childs including the parent node, which in my case wasn't usefull.


      In my 1st post, nodeChangingAre a is your parent node in question.

      And thanks for sharing your opinion.
      If you disagree please let me know, i have almost none exerience in programing, so if my thinking is wrong, would appreciated a notice.
      I'm applying this to a work i need to do, to the faculty.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        of course you could wrap nodes ... but every DOM operation to create or remove nodes is very 'expensive' so just using more nodes to make a script working isn't really an option. the script to which you have linked is here (to have it here to look at it better):
        Code:
        while ( node.hasChildNodes() ) {
            node.removeChild( node.firstChild );
        }
        this doesn't remove the parent node as you will see in the following test-case.
        Code:
        <html>
        <script type="text/javascript">
        
        function removeAllChildNodesFromParent(node) {
            while ( node.hasChildNodes() ) {
                node.removeChild( node.firstChild );
            }
        }
        
        </script>
        <body>
            <div id="pNode" style="border: 1px solid red;">
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
                <p>foo</p>
            </div>
            <button onclick="
                removeAllChildNodesFromParent(document.getElementById('pNode'));
            ">remove the child nodes</button>
        </body>
        </html>
        so the shown method removes all child nodes reliably from the parent node without! removing the parent node. You might notice that by seeing the red border of the div after the remove-operation.

        So in case your parent node was removed ... this would have had another reason.

        kind regards

        Comment

        • NKTA
          New Member
          • Jan 2010
          • 26

          #5
          Well you are right. But i think the problem here is what use i want to it.

          In my case its a multiple choice form. I create a dinamic div so therefore i create an input to indicate the number of multiple choices. With that input, "lets say n" i create:
          - n checkboxes
          - plus n textareas to insert answers to choose. (these 2 as child nodes)
          If i press button these elements will be added.
          i dont want to add another options before erasing previous (therefore this code)
          and adding again when options are cleared (which implies verify if he haves any child nodes)

          I have tested changing how you suggested previously and it does work, but i wanted to stop by adding one, next would give a warning message to erase actual ones.
          Thank for all your help.

          Code:
          if(!nodeChangingRadio.lastChild.hasChildNodes()){
          }

          In this case previous code works as a charm, and this "if" prevents by adding a new child, if already exists one. But still trying to add second time it returns that nodeParent.last Child its null or it aint an object.

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5388

            #6
            could you show what you want to try with the above example code? it would be much better to have a look at some concrete lines to see what the problem exactly is ...

            kind regards

            Comment

            • NKTA
              New Member
              • Jan 2010
              • 26

              #7
              Hi.

              Thats what i was thinking. I re-edit to remove as unnecessary parts as i could in the code and still manage to keep it to work. Due to another post, i have also removed any elements iunnecessary in the nodes.

              Try it on IE8 to seeu full action, but then on F and Opera, well ...

              So the interface is something like this:

              Code:
              <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
              <html>
              <head>
              	<title>Questionário Teórico</title>
              	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
              	<script type="text/javascript" src="script.js">
              	<*link rel="stylesheet" type="text/css" href="style.css">
              	</script>
              </head>
              <body>
              	<form action="#">
              		
              		<p align="center">Questionário de Questões Múltiplas</p>
              		<fieldset type="">
              		<legend>Pergunta:</legend>
              	
              		<p><textarea id="textArea" rows="5" cols="150"></textarea></p>
              		
              		<label>Número de opções para resposta (default = 4): <input type="text" size=2 name="Radio" id="radioButtons"/></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              		<input type="button" value="Criar Opções" id="criarOpcoes" style="background-color:#0000FF; color: #ffffff;" onClick="addRadioButtons();" />
              		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              		<input type="button" value="Apagar Opções" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
              		
              		<div id="radioButtonsChoice"><br/></div><br/>
              			
              		<p>
              		<label><input type="radio" name="nodeAction" />Adicionar Pergunta</label>
              		<label><input type="radio" name="nodeAction" />Apagar Pergunta</label>
              		<label><input type="radio" name="nodeAction" />Inserir antes de uma Pergunta</label>
              		<label><input type="radio" name="nodeAction" />Substituir Pergunta</label>
              		</p>
              			
              		
              		<p>Pergunta # <select type="" id="grafCount"></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              		<input type="submit" value="Efectuar acção !" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              		<!-- <input type="reset" value="Limpar Campos" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/></label></p> -->
              		<input type="button" value="Limpar Campos e Opções" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
              		
              		<p/>
              		</fieldset>
              	</form>
              	<div id="questionario"></div>
              </body>
              </html>

              The script is something like these:
              Code:
              window.onload = initAll;
              var nodeChangingArea;
              var nodeChangingRadio;
              var counter=0;
              
              function initAll() {
              	document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
              	nodeChangingArea = document.getElementById("questionario");
              	nodeChangingRadio = document.getElementById("radioButtonsChoice");
              }
              
              function addRadioButtons() {
              	var inRadio = document.getElementById("radioButtons").value;
              	var newChoice = document.createElement("form");
              	if(inRadio != 0){
              		if(isNaN(inRadio) || inRadio == "" ){
              			if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
              				for (var h=0; h<4; h++){
              					var newBox = document.createElement("input");
              					newBox.type = "checkbox";
              					newBox.id = "Box"
              					var newAnswer = document.createElement("textarea");
              					newAnswer.setAttribute("id","Answer");
              					newAnswer.setAttribute("rows","1");
              					newAnswer.setAttribute("cols","100");
              					var separateAnswer = document.createElement("br");
              					newChoice.appendChild(separateAnswer);						
              					newChoice.appendChild(newBox);									
              					newChoice.appendChild(newAnswer);								
              				}
              				nodeChangingRadio.appendChild(newChoice);
              			}else{alert("Apague as opções existentes e crie novas !");}
              			return(false);
              		}
              		if(inRadio != ""){
              			if( !isNaN(inRadio) && inRadio > 1 ){
              				if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
              					for(var l=0; l < inRadio ; l++){
              						var newBox = document.createElement("input");
              						newBox.type = "checkbox";
              						newBox.id = "Box";
              						var newAnswer = document.createElement("textarea");
              						newAnswer.setAttribute("id","Answer");
              						newAnswer.setAttribute("rows","1");
              						newAnswer.setAttribute("cols","100");
              						var separateAnswer = document.createElement("br");
              						newChoice.appendChild(separateAnswer);
              						newChoice.appendChild(newBox);
              						newChoice.appendChild(newAnswer);
              					}
              					nodeChangingRadio.appendChild(newChoice);
              				}else{alert("Apague as opções existentes e crie novas !");}
              			}else{alert("Número de opções inseridas é insuficiente ou número inválido !");}
              		}
              	}else{
              		alert("Não inseriu um número de opções !");
              	}
              	
              }
              
              function delNode() {
              	var delChoice = document.getElementById("grafCount").selectedIndex;
              	var allGrafs = nodeChangingArea.getElementsByTagName("pre");
              	var killGraf = allGrafs.item(delChoice);
              	nodeChangingArea.removeChild(killGraf);
              }
              
              function addNode() {
              	var inText = document.getElementById("textArea").value;
              	var newText = document.createTextNode(inText);
              	if(inText != 0){
              		if(nodeChangingRadio.lastChild.hasChildNodes(false)){									
              			var newGraf = document.createElement("pre");
              			newGraf.appendChild(newText);
              			clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
              			clone.id = "clone";
              			counter = clone.childNodes[1].getElementsByTagName("textarea").length;
              			while(counter!=0){
              				counter--;
              				var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;					
              				var newText = new Array();
              				newText[counter] = document.createElement(" ");
              				var newTextNode = document.createTextNode(textOption);
              				newText[counter].appendChild(newTextNode);
              				clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
              			}
              			clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
              			newGraf.appendChild(clone);
              			nodeChangingArea.appendChild(newGraf);								
              		}else{alert("Não criou nenhuma opção !!!");}
              	}else{alert("Não criou uma pergunta !!!");}
              }
              
              function clearForm(oForm){														
                var elements = oForm.elements; 												
                oForm.reset();
                resetOpcoes();																 
                for(i=0; i<elements.length; i++) {
              	if(elements[i].type != null){
              		field_type = elements[i].type.toLowerCase();
              		switch(field_type) {
              			case "text": 
              			case "password": 
              			case "textarea":
              	        case "hidden":	
              				elements[i].value = ""; 
              				break;
              			case "radio":
              			case "checkbox":
              				if (elements[i].checked) {
              					elements[i].checked = false; 
              				}
              				break;
              			case "select-one":
              			case "select-multi":
              				elements[i].selectedIndex = -1;
              				break;
              			default: 
              				break;
              			}
              		}	
              	}
              }
              
              function resetOpcoes(){
              	if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
              		while (nodeChangingRadio.lastChild.hasChildNodes()) {	// while (nodeChangingRadio.lastChild.hasChildNodes()) {									
              			nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);							
              		}
              	}
              }
              
              function insertNode() {
              	var inChoice = document.getElementById("grafCount").selectedIndex;
              	var inText = document.getElementById("textArea").value;
              	if(inText != 0){ 
              		if(nodeChangingRadio.lastChild.hasChildNodes(false)){		
              			var newText = document.createTextNode(inText);
              			var newGraf = document.createElement("pre");
              			newGraf.appendChild(newText);
              			var allGrafs = nodeChangingArea.getElementsByTagName("pre");
              			var oldGraf = allGrafs.item(inChoice);
              			clone = nodeChangingRadio.cloneNode(true);
              			clone.id = "clone";
              			counter = clone.childNodes[1].getElementsByTagName("textarea").length;		
              			while(counter!=0){
              				counter--;
              				var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
              				var newText = new Array();
              				newText[counter] = document.createElement(" ");
              				var newTextNode = document.createTextNode(textOption);
              				newText[counter].appendChild(newTextNode);
              				clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
              			}
              			clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
              			newGraf.appendChild(clone);	
              			nodeChangingArea.appendChild(newGraf);
              			nodeChangingArea.insertBefore(newGraf,oldGraf);
              		}else{alert("Não criou nenhuma opção !!!");}
              	}else{alert("Não inseriu uma pergunta !!!");}
              }
              
              function replaceNode() {
              	var inChoice = document.getElementById("grafCount").selectedIndex;
              	var inText = document.getElementById("textArea").value;
              	if(inText != 0){ 
              		if(nodeChangingRadio.lastChild.hasChildNodes(false)){
              			var newText = document.createTextNode(inText);
              			var newGraf = document.createElement("pre");
              			newGraf.appendChild(newText);
              			var allGrafs = nodeChangingArea.getElementsByTagName("pre");
              			var oldGraf = allGrafs.item(inChoice);
              			clone = nodeChangingRadio.cloneNode(true);
              			clone.id = "clone";
              			counter = clone.childNodes[1].getElementsByTagName("textarea").length;		
              			while(counter!=0){
              				counter--;
              				var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
              				var newText = new Array();
              				newText[counter] = document.createElement(" ");
              				var newTextNode = document.createTextNode(textOption);
              				newText[counter].appendChild(newTextNode);
              				clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
              			}
              			clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
              			newGraf.appendChild(clone);	
              			nodeChangingArea.appendChild(newGraf);
              			nodeChangingArea.replaceChild(newGraf,oldGraf);
              		}else{alert("Não criou nenhuma opção !!!");}
              	}else{alert("Não inseriu uma pergunta !!!");}
              }
              
              function nodeChanger()  {
              	var actionType = -1;
              	var currentPgraphCount = document.getElementsByTagName("pre").length;
              	var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
              	for (var i=0; i<radioButtonSet.length; i++) {
              		if (radioButtonSet[i].checked) {
              			actionType = i;
              		}
              	}
              	switch(actionType) {
              		case 0:
              			addNode();
              			break;
              		case 1:
              			if (currentPgraphCount > 0) {
              				delNode();
              				break;
              			}
              		case 2:
              			if (currentPgraphCount > 0) {
              				insertNode();
              				break;
              			}
              		case 3:
              			if (currentPgraphCount > 0) {
              				replaceNode();
              				break
              			}
              		default:
              			alert("Nenhuma opção foi escolhida !");
              	}
              	document.getElementById("grafCount").options.length = 0;
              	for (i=0; i<nodeChangingArea.getElementsByTagName("pre").length; i++) {
              		document.getElementById("grafCount").options[i] = new Option(i+1);
              	}
              	return false;
              }

              Comment

              • gits
                Recognized Expert Moderator Expert
                • May 2007
                • 5388

                #8
                hmmm ... what am I supposed to do/see from that? i cannot understand that language ... just clicking like a blind one in that page that loads up then doesn't help anything. so what is the exact problem here? ... how could it be reproduced?

                Comment

                • NKTA
                  New Member
                  • Jan 2010
                  • 26

                  #9
                  the problem is that it works very well on IE8 but not in mozilla or opera. Gonna edit the code so that you understand .


                  Code:
                  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                  <html>
                  <head>
                      <title>Multiple question form</title>
                      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                      <script type="text/javascript" src="script.js">
                      <*link rel="stylesheet" type="text/css" href="style.css">
                      </script>
                  </head>
                  <body>
                      <form action="#">
                   
                          <p align="center">Multiple question form</p>
                          <fieldset type="">
                          <legend>Question:</legend>
                   
                          <p><textarea id="textArea" rows="5" cols="150"></textarea></p>
                   
                          <label>Number of options (default = 4): <input type="text" size=2 name="Radio" id="radioButtons"/></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <input type="button" value="Create Options" id="criarOpcoes" style="background-color:#0000FF; color: #ffffff;" onClick="addRadioButtons();" />
                          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <input type="button" value="Erase Options" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
                   
                          <div id="radioButtonsChoice"><br/></div><br/>
                   
                          <p>
                          <label><input type="radio" name="nodeAction" />Add Question</label>
                          <label><input type="radio" name="nodeAction" />Erase Question</label>
                          <label><input type="radio" name="nodeAction" />Insert before a Question</label>
                          <label><input type="radio" name="nodeAction" />Replace Question</label>
                          </p>
                   
                   
                          <p>Question # <select type="" id="grafCount"></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <input type="submit" value="Create multiple choice question!" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                          <!-- <input type="reset" value="Erase fields" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/></label></p> -->
                          <input type="button" value="Erase fields and options" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
                   
                          <p/>
                          </fieldset>
                      </form>
                      <div id="questionario"></div>
                  </body>
                  </html>

                  Here's the Js edited:

                  Code:
                  window.onload = initAll;
                  var nodeChangingArea;
                  var nodeChangingRadio;
                  var counter=0;
                   
                  function initAll() {
                      document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
                      nodeChangingArea = document.getElementById("questionario");
                      nodeChangingRadio = document.getElementById("radioButtonsChoice");
                  }
                   
                  function addRadioButtons() {
                      var inRadio = document.getElementById("radioButtons").value;
                      var newChoice = document.createElement("form");
                      if(inRadio != 0){
                          if(isNaN(inRadio) || inRadio == "" ){
                              if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
                                  for (var h=0; h<4; h++){
                                      var newBox = document.createElement("input");
                                      newBox.type = "checkbox";
                                      newBox.id = "Box"
                                      var newAnswer = document.createElement("textarea");
                                      newAnswer.setAttribute("id","Answer");
                                      newAnswer.setAttribute("rows","1");
                                      newAnswer.setAttribute("cols","100");
                                      var separateAnswer = document.createElement("br");
                                      newChoice.appendChild(separateAnswer);                        
                                      newChoice.appendChild(newBox);                                    
                                      newChoice.appendChild(newAnswer);                                
                                  }
                                  nodeChangingRadio.appendChild(newChoice);
                              }else{alert("Erase the existing options and create new !");}
                              return(false);
                          }
                          if(inRadio != ""){
                              if( !isNaN(inRadio) && inRadio > 1 ){
                                  if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
                                      for(var l=0; l < inRadio ; l++){
                                          var newBox = document.createElement("input");
                                          newBox.type = "checkbox";
                                          newBox.id = "Box";
                                          var newAnswer = document.createElement("textarea");
                                          newAnswer.setAttribute("id","Answer");
                                          newAnswer.setAttribute("rows","1");
                                          newAnswer.setAttribute("cols","100");
                                          var separateAnswer = document.createElement("br");
                                          newChoice.appendChild(separateAnswer);
                                          newChoice.appendChild(newBox);
                                          newChoice.appendChild(newAnswer);
                                      }
                                      nodeChangingRadio.appendChild(newChoice);
                                  }else{alert("Erase existing options and create new !");}
                              }else{alert("Number of options inserted aren' t enoough or number invalid !");}
                          }
                      }else{
                          alert("You didn't inserted a number of options!");
                      }
                   
                  }
                   
                  function delNode() {
                      var delChoice = document.getElementById("grafCount").selectedIndex;
                      var allGrafs = nodeChangingArea.getElementsByTagName("pre");
                      var killGraf = allGrafs.item(delChoice);
                      nodeChangingArea.removeChild(killGraf);
                  }
                   
                  function addNode() {
                      var inText = document.getElementById("textArea").value;
                      var newText = document.createTextNode(inText);
                      if(inText != 0){
                          if(nodeChangingRadio.lastChild.hasChildNodes(false)){                                    
                              var newGraf = document.createElement("pre");
                              newGraf.appendChild(newText);
                              clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
                              clone.id = "clone";
                              counter = clone.childNodes[1].getElementsByTagName("textarea").length;
                              while(counter!=0){
                                  counter--;
                                  var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;                    
                                  var newText = new Array();
                                  newText[counter] = document.createElement(" ");
                                  var newTextNode = document.createTextNode(textOption);
                                  newText[counter].appendChild(newTextNode);
                                  clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                              }
                              clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
                              newGraf.appendChild(clone);
                              nodeChangingArea.appendChild(newGraf);                                
                          }else{alert("You didn't created an option !!!");}
                      }else{alert("You didn't created an question !!!");}
                  }
                   
                  function clearForm(oForm){                                                        
                    var elements = oForm.elements;                                                 
                    oForm.reset();
                    resetOpcoes();                                                                 
                    for(i=0; i<elements.length; i++) {
                      if(elements[i].type != null){
                          field_type = elements[i].type.toLowerCase();
                          switch(field_type) {
                              case "text": 
                              case "password": 
                              case "textarea":
                              case "hidden":    
                                  elements[i].value = ""; 
                                  break;
                              case "radio":
                              case "checkbox":
                                  if (elements[i].checked) {
                                      elements[i].checked = false; 
                                  }
                                  break;
                              case "select-one":
                              case "select-multi":
                                  elements[i].selectedIndex = -1;
                                  break;
                              default: 
                                  break;
                              }
                          }    
                      }
                  }
                   
                  function resetOpcoes(){
                      if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
                          while (nodeChangingRadio.lastChild.hasChildNodes()) {    // while (nodeChangingRadio.lastChild.hasChildNodes()) {                                    
                              nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);                            
                          }
                      }
                  }
                   
                  function insertNode() {
                      var inChoice = document.getElementById("grafCount").selectedIndex;
                      var inText = document.getElementById("textArea").value;
                      if(inText != 0){ 
                          if(nodeChangingRadio.lastChild.hasChildNodes(false)){        
                              var newText = document.createTextNode(inText);
                              var newGraf = document.createElement("pre");
                              newGraf.appendChild(newText);
                              var allGrafs = nodeChangingArea.getElementsByTagName("pre");
                              var oldGraf = allGrafs.item(inChoice);
                              clone = nodeChangingRadio.cloneNode(true);
                              clone.id = "clone";
                              counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
                              while(counter!=0){
                                  counter--;
                                  var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
                                  var newText = new Array();
                                  newText[counter] = document.createElement(" ");
                                  var newTextNode = document.createTextNode(textOption);
                                  newText[counter].appendChild(newTextNode);
                                  clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                              }
                              clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
                              newGraf.appendChild(clone);    
                              nodeChangingArea.appendChild(newGraf);
                              nodeChangingArea.insertBefore(newGraf,oldGraf);
                          }else{alert("You didn't created an option !!!");}
                      }else{alert("You didn't created an question !!!");}
                  }
                   
                  function replaceNode() {
                      var inChoice = document.getElementById("grafCount").selectedIndex;
                      var inText = document.getElementById("textArea").value;
                      if(inText != 0){ 
                          if(nodeChangingRadio.lastChild.hasChildNodes(false)){
                              var newText = document.createTextNode(inText);
                              var newGraf = document.createElement("pre");
                              newGraf.appendChild(newText);
                              var allGrafs = nodeChangingArea.getElementsByTagName("pre");
                              var oldGraf = allGrafs.item(inChoice);
                              clone = nodeChangingRadio.cloneNode(true);
                              clone.id = "clone";
                              counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
                              while(counter!=0){
                                  counter--;
                                  var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
                                  var newText = new Array();
                                  newText[counter] = document.createElement(" ");
                                  var newTextNode = document.createTextNode(textOption);
                                  newText[counter].appendChild(newTextNode);
                                  clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                              }
                              clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
                              newGraf.appendChild(clone);    
                              nodeChangingArea.appendChild(newGraf);
                              nodeChangingArea.replaceChild(newGraf,oldGraf);
                          }else{alert("You didn't created an option !!!");}
                      }else{alert("You didn't created an question !!!");}
                  }
                   
                  function nodeChanger()  {
                      var actionType = -1;
                      var currentPgraphCount = document.getElementsByTagName("pre").length;
                      var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
                      for (var i=0; i<radioButtonSet.length; i++) {
                          if (radioButtonSet[i].checked) {
                              actionType = i;
                          }
                      }
                      switch(actionType) {
                          case 0:
                              addNode();
                              break;
                          case 1:
                              if (currentPgraphCount > 0) {
                                  delNode();
                                  break;
                              }
                          case 2:
                              if (currentPgraphCount > 0) {
                                  insertNode();
                                  break;
                              }
                          case 3:
                              if (currentPgraphCount > 0) {
                                  replaceNode();
                                  break
                              }
                          default:
                              alert("Nenhuma opção foi escolhida !");
                      }
                      document.getElementById("grafCount").options.length = 0;
                      for (i=0; i<nodeChangingArea.getElementsByTagName("pre").length; i++) {
                          document.getElementById("grafCount").options[i] = new Option(i+1);
                      }
                      return false;
                  }


                  Now about issues in the code, in opera and firefox i can't add multiple question form, it seems that it stops completely.
                  In IE8, when wirting in textare, any enter pressed, when removing its textarea.value and wiring it in another place, except for first line, all text appeas with a initial space.
                  Another problem is that i want to limit the numbers of words that fit in the screen, just type a letter untill it fills 2 lines, add a question and see what happens to new question.

                  Comment

                  • NKTA
                    New Member
                    • Jan 2010
                    • 26

                    #10
                    Just added a line of code that prevents the script opera from ignoring or crashing. Now it simply doesn't execute addNode, previously it wiped all information in page and restarted the script.
                    Code:
                    	var inRadio = document.getElementById("radioButtons").value;
                    	var inRadio2 = parseInt(inRadio);
                                if ( isNaN( inRadio ) || inRadio2 == " "  ){ ... }
                                if ( ! isNaN( inRadio ) && inRadio2  > 1 ){ ... }
                    It seems its better to deal with the "parseInt" then its ".value" in conditions like "if" (at least in opera, IE8 doesn't seem to care).

                    Comment

                    • Dormilich
                      Recognized Expert Expert
                      • Aug 2008
                      • 8694

                      #11
                      and opera starts crashing the script again. So i'mm guessing that whats crashing my script is the ".value". Need to do alerts to test the code.
                      better use Opera’s Dragonfly (developer tool)

                      Comment

                      • NKTA
                        New Member
                        • Jan 2010
                        • 26

                        #12
                        Thank You, but i'm using it.

                        But the error isn't specific. It's the same as said in last post.
                        Since it doesn't give me a specific line of error, you could say i'm fishing.

                        BR

                        Code:
                        Line: ?
                        Error: ?	Unhandled exception: [Object DOMException]
                        
                        file://.../Trabalho.Pratico/QuestQuestoesMultiplas/QuestTeorico.html?Radio=2&nodeAction=on
                        Unhandled exception: [Object DOMException]
                        name: Error
                        message: INVALID_CHARACTER_ERR
                        stacktrace: n/a; see  opera:config#UserPrefs|Exceptions Have Stacktrace
                        Just remembered myself, i also have firefox + firebug
                        Which reports:
                        Code:
                        "enabling javascript debugger to support console"
                        String contains an invalid character" code: "5
                        [Break on this error] newText[counter] = document.createElement(" ");

                        Well, LOL.
                        Works 100% on opera and IE8, Firefox works, well 90%. Replace the empty element by a span and it seems that in firefox does recognize it (the text doesn't show in front of the checkbox).

                        The error which made my script crashing was that IE8 is the only to support empty elements to append as a child, text.

                        I think that IE8 is interpreting my key "Enter" as a <BR> in the "textarea" since i pressed it, in the choices will appear a white line between phrases separating them.

                        By the way i want to limit the lines writen on the "textarea" to the screen and not going on forever to the right. Can anyone help me on that ?

                        Comment

                        • Dormilich
                          Recognized Expert Expert
                          • Aug 2008
                          • 8694

                          #13
                          you mean the cols and rows attributes?

                          Comment

                          • NKTA
                            New Member
                            • Jan 2010
                            • 26

                            #14
                            Nope. I already edit the rows and cols to the ideal size of the textarea. The problem is that the text captured from the "textarea" input when is re-writen as a textnode it does not respect the screen bondaries, i.e. it continues all to the right whrn is written in simple text on the html. Its just the same as writing simple text in html, it goes all the way to the right.

                            Comment

                            • gits
                              Recognized Expert Moderator Expert
                              • May 2007
                              • 5388

                              #15
                              hmmm ... so you want to force the manual linebreaks to a 'html'-linebreak?

                              you might do that with a replace() like:
                              Code:
                              var myHtmlText = textAreaText.replace(/\n/g, '<br/>');
                              kind regards

                              Comment

                              Working...