By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,238 Members | 1,320 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,238 IT Pros & Developers. It's quick & easy.

Javascript Erase all Nodes at once.

P: 26
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:
Expand|Select|Wrap|Line Numbers
  1. function resetAllNodes(){
  2.     if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
  3.         while (nodeChangingRadio.lastChild.hasChildNodes()) {    
  4.                       nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);
  5.                 }
  6.     }
  7. }
  8.  

This way, i erase all childs in a node, and still possilble add again.
Jan 27 '10 #1
Share this Question
Share on Google+
23 Replies


gits
Expert Mod 5K+
P: 5,390
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
Jan 29 '10 #2

P: 26
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:
Expand|Select|Wrap|Line Numbers
  1. // Create the textnode or empty node
  2. var empty = document.createElement("var that has the text/string/numbers value"); // or var empty = createTextNode(something.value);
  3. // and then
  4. var p = document.createElement("p");
  5. p.appendChild(empty);
  6.  
  7. // Now only thing missing is appending child p to the parent node you are dealing
  8. // 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.
  9.  
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, nodeChangingArea 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.
Jan 29 '10 #3

gits
Expert Mod 5K+
P: 5,390
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):
Expand|Select|Wrap|Line Numbers
  1. while ( node.hasChildNodes() ) {
  2.     node.removeChild( node.firstChild );
  3. }
this doesn't remove the parent node as you will see in the following test-case.
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <script type="text/javascript">
  3.  
  4. function removeAllChildNodesFromParent(node) {
  5.     while ( node.hasChildNodes() ) {
  6.         node.removeChild( node.firstChild );
  7.     }
  8. }
  9.  
  10. </script>
  11. <body>
  12.     <div id="pNode" style="border: 1px solid red;">
  13.         <p>foo</p>
  14.         <p>foo</p>
  15.         <p>foo</p>
  16.         <p>foo</p>
  17.         <p>foo</p>
  18.         <p>foo</p>
  19.         <p>foo</p>
  20.         <p>foo</p>
  21.         <p>foo</p>
  22.         <p>foo</p>
  23.         <p>foo</p>
  24.         <p>foo</p>
  25.     </div>
  26.     <button onclick="
  27.         removeAllChildNodesFromParent(document.getElementById('pNode'));
  28.     ">remove the child nodes</button>
  29. </body>
  30. </html>
  31.  
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
Jan 29 '10 #4

P: 26
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.

Expand|Select|Wrap|Line Numbers
  1. if(!nodeChangingRadio.lastChild.hasChildNodes()){
  2. }
  3.  

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.lastChild its null or it aint an object.
Jan 29 '10 #5

gits
Expert Mod 5K+
P: 5,390
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
Jan 29 '10 #6

P: 26
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:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4.     <title>Questionário Teórico</title>
  5.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  6.     <script type="text/javascript" src="script.js">
  7.     <*link rel="stylesheet" type="text/css" href="style.css">
  8.     </script>
  9. </head>
  10. <body>
  11.     <form action="#">
  12.  
  13.         <p align="center">Questionário de Questões Múltiplas</p>
  14.         <fieldset type="">
  15.         <legend>Pergunta:</legend>
  16.  
  17.         <p><textarea id="textArea" rows="5" cols="150"></textarea></p>
  18.  
  19.         <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;
  20.         <input type="button" value="Criar Opções" id="criarOpcoes" style="background-color:#0000FF; color: #ffffff;" onClick="addRadioButtons();" />
  21.         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  22.         <input type="button" value="Apagar Opções" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
  23.  
  24.         <div id="radioButtonsChoice"><br/></div><br/>
  25.  
  26.         <p>
  27.         <label><input type="radio" name="nodeAction" />Adicionar Pergunta</label>
  28.         <label><input type="radio" name="nodeAction" />Apagar Pergunta</label>
  29.         <label><input type="radio" name="nodeAction" />Inserir antes de uma Pergunta</label>
  30.         <label><input type="radio" name="nodeAction" />Substituir Pergunta</label>
  31.         </p>
  32.  
  33.  
  34.         <p>Pergunta # <select type="" id="grafCount"></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  35.         <input type="submit" value="Efectuar acção !" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  36.         <!-- <input type="reset" value="Limpar Campos" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/></label></p> -->
  37.         <input type="button" value="Limpar Campos e Opções" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
  38.  
  39.         <p/>
  40.         </fieldset>
  41.     </form>
  42.     <div id="questionario"></div>
  43. </body>
  44. </html>
  45.  
  46.  

The script is something like these:
Expand|Select|Wrap|Line Numbers
  1. window.onload = initAll;
  2. var nodeChangingArea;
  3. var nodeChangingRadio;
  4. var counter=0;
  5.  
  6. function initAll() {
  7.     document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
  8.     nodeChangingArea = document.getElementById("questionario");
  9.     nodeChangingRadio = document.getElementById("radioButtonsChoice");
  10. }
  11.  
  12. function addRadioButtons() {
  13.     var inRadio = document.getElementById("radioButtons").value;
  14.     var newChoice = document.createElement("form");
  15.     if(inRadio != 0){
  16.         if(isNaN(inRadio) || inRadio == "" ){
  17.             if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
  18.                 for (var h=0; h<4; h++){
  19.                     var newBox = document.createElement("input");
  20.                     newBox.type = "checkbox";
  21.                     newBox.id = "Box"
  22.                     var newAnswer = document.createElement("textarea");
  23.                     newAnswer.setAttribute("id","Answer");
  24.                     newAnswer.setAttribute("rows","1");
  25.                     newAnswer.setAttribute("cols","100");
  26.                     var separateAnswer = document.createElement("br");
  27.                     newChoice.appendChild(separateAnswer);                        
  28.                     newChoice.appendChild(newBox);                                    
  29.                     newChoice.appendChild(newAnswer);                                
  30.                 }
  31.                 nodeChangingRadio.appendChild(newChoice);
  32.             }else{alert("Apague as opções existentes e crie novas !");}
  33.             return(false);
  34.         }
  35.         if(inRadio != ""){
  36.             if( !isNaN(inRadio) && inRadio > 1 ){
  37.                 if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
  38.                     for(var l=0; l < inRadio ; l++){
  39.                         var newBox = document.createElement("input");
  40.                         newBox.type = "checkbox";
  41.                         newBox.id = "Box";
  42.                         var newAnswer = document.createElement("textarea");
  43.                         newAnswer.setAttribute("id","Answer");
  44.                         newAnswer.setAttribute("rows","1");
  45.                         newAnswer.setAttribute("cols","100");
  46.                         var separateAnswer = document.createElement("br");
  47.                         newChoice.appendChild(separateAnswer);
  48.                         newChoice.appendChild(newBox);
  49.                         newChoice.appendChild(newAnswer);
  50.                     }
  51.                     nodeChangingRadio.appendChild(newChoice);
  52.                 }else{alert("Apague as opções existentes e crie novas !");}
  53.             }else{alert("Número de opções inseridas é insuficiente ou número inválido !");}
  54.         }
  55.     }else{
  56.         alert("Não inseriu um número de opções !");
  57.     }
  58.  
  59. }
  60.  
  61. function delNode() {
  62.     var delChoice = document.getElementById("grafCount").selectedIndex;
  63.     var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  64.     var killGraf = allGrafs.item(delChoice);
  65.     nodeChangingArea.removeChild(killGraf);
  66. }
  67.  
  68. function addNode() {
  69.     var inText = document.getElementById("textArea").value;
  70.     var newText = document.createTextNode(inText);
  71.     if(inText != 0){
  72.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){                                    
  73.             var newGraf = document.createElement("pre");
  74.             newGraf.appendChild(newText);
  75.             clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
  76.             clone.id = "clone";
  77.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;
  78.             while(counter!=0){
  79.                 counter--;
  80.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;                    
  81.                 var newText = new Array();
  82.                 newText[counter] = document.createElement(" ");
  83.                 var newTextNode = document.createTextNode(textOption);
  84.                 newText[counter].appendChild(newTextNode);
  85.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  86.             }
  87.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  88.             newGraf.appendChild(clone);
  89.             nodeChangingArea.appendChild(newGraf);                                
  90.         }else{alert("Não criou nenhuma opção !!!");}
  91.     }else{alert("Não criou uma pergunta !!!");}
  92. }
  93.  
  94. function clearForm(oForm){                                                        
  95.   var elements = oForm.elements;                                                 
  96.   oForm.reset();
  97.   resetOpcoes();                                                                 
  98.   for(i=0; i<elements.length; i++) {
  99.     if(elements[i].type != null){
  100.         field_type = elements[i].type.toLowerCase();
  101.         switch(field_type) {
  102.             case "text": 
  103.             case "password": 
  104.             case "textarea":
  105.             case "hidden":    
  106.                 elements[i].value = ""; 
  107.                 break;
  108.             case "radio":
  109.             case "checkbox":
  110.                 if (elements[i].checked) {
  111.                     elements[i].checked = false; 
  112.                 }
  113.                 break;
  114.             case "select-one":
  115.             case "select-multi":
  116.                 elements[i].selectedIndex = -1;
  117.                 break;
  118.             default: 
  119.                 break;
  120.             }
  121.         }    
  122.     }
  123. }
  124.  
  125. function resetOpcoes(){
  126.     if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
  127.         while (nodeChangingRadio.lastChild.hasChildNodes()) {    // while (nodeChangingRadio.lastChild.hasChildNodes()) {                                    
  128.             nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);                            
  129.         }
  130.     }
  131. }
  132.  
  133. function insertNode() {
  134.     var inChoice = document.getElementById("grafCount").selectedIndex;
  135.     var inText = document.getElementById("textArea").value;
  136.     if(inText != 0){ 
  137.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){        
  138.             var newText = document.createTextNode(inText);
  139.             var newGraf = document.createElement("pre");
  140.             newGraf.appendChild(newText);
  141.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  142.             var oldGraf = allGrafs.item(inChoice);
  143.             clone = nodeChangingRadio.cloneNode(true);
  144.             clone.id = "clone";
  145.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
  146.             while(counter!=0){
  147.                 counter--;
  148.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  149.                 var newText = new Array();
  150.                 newText[counter] = document.createElement(" ");
  151.                 var newTextNode = document.createTextNode(textOption);
  152.                 newText[counter].appendChild(newTextNode);
  153.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  154.             }
  155.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  156.             newGraf.appendChild(clone);    
  157.             nodeChangingArea.appendChild(newGraf);
  158.             nodeChangingArea.insertBefore(newGraf,oldGraf);
  159.         }else{alert("Não criou nenhuma opção !!!");}
  160.     }else{alert("Não inseriu uma pergunta !!!");}
  161. }
  162.  
  163. function replaceNode() {
  164.     var inChoice = document.getElementById("grafCount").selectedIndex;
  165.     var inText = document.getElementById("textArea").value;
  166.     if(inText != 0){ 
  167.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){
  168.             var newText = document.createTextNode(inText);
  169.             var newGraf = document.createElement("pre");
  170.             newGraf.appendChild(newText);
  171.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  172.             var oldGraf = allGrafs.item(inChoice);
  173.             clone = nodeChangingRadio.cloneNode(true);
  174.             clone.id = "clone";
  175.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
  176.             while(counter!=0){
  177.                 counter--;
  178.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  179.                 var newText = new Array();
  180.                 newText[counter] = document.createElement(" ");
  181.                 var newTextNode = document.createTextNode(textOption);
  182.                 newText[counter].appendChild(newTextNode);
  183.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  184.             }
  185.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  186.             newGraf.appendChild(clone);    
  187.             nodeChangingArea.appendChild(newGraf);
  188.             nodeChangingArea.replaceChild(newGraf,oldGraf);
  189.         }else{alert("Não criou nenhuma opção !!!");}
  190.     }else{alert("Não inseriu uma pergunta !!!");}
  191. }
  192.  
  193. function nodeChanger()  {
  194.     var actionType = -1;
  195.     var currentPgraphCount = document.getElementsByTagName("pre").length;
  196.     var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
  197.     for (var i=0; i<radioButtonSet.length; i++) {
  198.         if (radioButtonSet[i].checked) {
  199.             actionType = i;
  200.         }
  201.     }
  202.     switch(actionType) {
  203.         case 0:
  204.             addNode();
  205.             break;
  206.         case 1:
  207.             if (currentPgraphCount > 0) {
  208.                 delNode();
  209.                 break;
  210.             }
  211.         case 2:
  212.             if (currentPgraphCount > 0) {
  213.                 insertNode();
  214.                 break;
  215.             }
  216.         case 3:
  217.             if (currentPgraphCount > 0) {
  218.                 replaceNode();
  219.                 break
  220.             }
  221.         default:
  222.             alert("Nenhuma opção foi escolhida !");
  223.     }
  224.     document.getElementById("grafCount").options.length = 0;
  225.     for (i=0; i<nodeChangingArea.getElementsByTagName("pre").length; i++) {
  226.         document.getElementById("grafCount").options[i] = new Option(i+1);
  227.     }
  228.     return false;
  229. }
  230.  
Jan 29 '10 #7

gits
Expert Mod 5K+
P: 5,390
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?
Jan 30 '10 #8

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


Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4.     <title>Multiple question form</title>
  5.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  6.     <script type="text/javascript" src="script.js">
  7.     <*link rel="stylesheet" type="text/css" href="style.css">
  8.     </script>
  9. </head>
  10. <body>
  11.     <form action="#">
  12.  
  13.         <p align="center">Multiple question form</p>
  14.         <fieldset type="">
  15.         <legend>Question:</legend>
  16.  
  17.         <p><textarea id="textArea" rows="5" cols="150"></textarea></p>
  18.  
  19.         <label>Number of options (default = 4): <input type="text" size=2 name="Radio" id="radioButtons"/></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  20.         <input type="button" value="Create Options" id="criarOpcoes" style="background-color:#0000FF; color: #ffffff;" onClick="addRadioButtons();" />
  21.         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  22.         <input type="button" value="Erase Options" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
  23.  
  24.         <div id="radioButtonsChoice"><br/></div><br/>
  25.  
  26.         <p>
  27.         <label><input type="radio" name="nodeAction" />Add Question</label>
  28.         <label><input type="radio" name="nodeAction" />Erase Question</label>
  29.         <label><input type="radio" name="nodeAction" />Insert before a Question</label>
  30.         <label><input type="radio" name="nodeAction" />Replace Question</label>
  31.         </p>
  32.  
  33.  
  34.         <p>Question # <select type="" id="grafCount"></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  35.         <input type="submit" value="Create multiple choice question!" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  36.         <!-- <input type="reset" value="Erase fields" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/></label></p> -->
  37.         <input type="button" value="Erase fields and options" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
  38.  
  39.         <p/>
  40.         </fieldset>
  41.     </form>
  42.     <div id="questionario"></div>
  43. </body>
  44. </html>
  45.  
  46.  
  47.  

Here's the Js edited:

Expand|Select|Wrap|Line Numbers
  1. window.onload = initAll;
  2. var nodeChangingArea;
  3. var nodeChangingRadio;
  4. var counter=0;
  5.  
  6. function initAll() {
  7.     document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
  8.     nodeChangingArea = document.getElementById("questionario");
  9.     nodeChangingRadio = document.getElementById("radioButtonsChoice");
  10. }
  11.  
  12. function addRadioButtons() {
  13.     var inRadio = document.getElementById("radioButtons").value;
  14.     var newChoice = document.createElement("form");
  15.     if(inRadio != 0){
  16.         if(isNaN(inRadio) || inRadio == "" ){
  17.             if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
  18.                 for (var h=0; h<4; h++){
  19.                     var newBox = document.createElement("input");
  20.                     newBox.type = "checkbox";
  21.                     newBox.id = "Box"
  22.                     var newAnswer = document.createElement("textarea");
  23.                     newAnswer.setAttribute("id","Answer");
  24.                     newAnswer.setAttribute("rows","1");
  25.                     newAnswer.setAttribute("cols","100");
  26.                     var separateAnswer = document.createElement("br");
  27.                     newChoice.appendChild(separateAnswer);                        
  28.                     newChoice.appendChild(newBox);                                    
  29.                     newChoice.appendChild(newAnswer);                                
  30.                 }
  31.                 nodeChangingRadio.appendChild(newChoice);
  32.             }else{alert("Erase the existing options and create new !");}
  33.             return(false);
  34.         }
  35.         if(inRadio != ""){
  36.             if( !isNaN(inRadio) && inRadio > 1 ){
  37.                 if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
  38.                     for(var l=0; l < inRadio ; l++){
  39.                         var newBox = document.createElement("input");
  40.                         newBox.type = "checkbox";
  41.                         newBox.id = "Box";
  42.                         var newAnswer = document.createElement("textarea");
  43.                         newAnswer.setAttribute("id","Answer");
  44.                         newAnswer.setAttribute("rows","1");
  45.                         newAnswer.setAttribute("cols","100");
  46.                         var separateAnswer = document.createElement("br");
  47.                         newChoice.appendChild(separateAnswer);
  48.                         newChoice.appendChild(newBox);
  49.                         newChoice.appendChild(newAnswer);
  50.                     }
  51.                     nodeChangingRadio.appendChild(newChoice);
  52.                 }else{alert("Erase existing options and create new !");}
  53.             }else{alert("Number of options inserted aren' t enoough or number invalid !");}
  54.         }
  55.     }else{
  56.         alert("You didn't inserted a number of options!");
  57.     }
  58.  
  59. }
  60.  
  61. function delNode() {
  62.     var delChoice = document.getElementById("grafCount").selectedIndex;
  63.     var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  64.     var killGraf = allGrafs.item(delChoice);
  65.     nodeChangingArea.removeChild(killGraf);
  66. }
  67.  
  68. function addNode() {
  69.     var inText = document.getElementById("textArea").value;
  70.     var newText = document.createTextNode(inText);
  71.     if(inText != 0){
  72.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){                                    
  73.             var newGraf = document.createElement("pre");
  74.             newGraf.appendChild(newText);
  75.             clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
  76.             clone.id = "clone";
  77.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;
  78.             while(counter!=0){
  79.                 counter--;
  80.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;                    
  81.                 var newText = new Array();
  82.                 newText[counter] = document.createElement(" ");
  83.                 var newTextNode = document.createTextNode(textOption);
  84.                 newText[counter].appendChild(newTextNode);
  85.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  86.             }
  87.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  88.             newGraf.appendChild(clone);
  89.             nodeChangingArea.appendChild(newGraf);                                
  90.         }else{alert("You didn't created an option !!!");}
  91.     }else{alert("You didn't created an question !!!");}
  92. }
  93.  
  94. function clearForm(oForm){                                                        
  95.   var elements = oForm.elements;                                                 
  96.   oForm.reset();
  97.   resetOpcoes();                                                                 
  98.   for(i=0; i<elements.length; i++) {
  99.     if(elements[i].type != null){
  100.         field_type = elements[i].type.toLowerCase();
  101.         switch(field_type) {
  102.             case "text": 
  103.             case "password": 
  104.             case "textarea":
  105.             case "hidden":    
  106.                 elements[i].value = ""; 
  107.                 break;
  108.             case "radio":
  109.             case "checkbox":
  110.                 if (elements[i].checked) {
  111.                     elements[i].checked = false; 
  112.                 }
  113.                 break;
  114.             case "select-one":
  115.             case "select-multi":
  116.                 elements[i].selectedIndex = -1;
  117.                 break;
  118.             default: 
  119.                 break;
  120.             }
  121.         }    
  122.     }
  123. }
  124.  
  125. function resetOpcoes(){
  126.     if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
  127.         while (nodeChangingRadio.lastChild.hasChildNodes()) {    // while (nodeChangingRadio.lastChild.hasChildNodes()) {                                    
  128.             nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);                            
  129.         }
  130.     }
  131. }
  132.  
  133. function insertNode() {
  134.     var inChoice = document.getElementById("grafCount").selectedIndex;
  135.     var inText = document.getElementById("textArea").value;
  136.     if(inText != 0){ 
  137.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){        
  138.             var newText = document.createTextNode(inText);
  139.             var newGraf = document.createElement("pre");
  140.             newGraf.appendChild(newText);
  141.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  142.             var oldGraf = allGrafs.item(inChoice);
  143.             clone = nodeChangingRadio.cloneNode(true);
  144.             clone.id = "clone";
  145.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
  146.             while(counter!=0){
  147.                 counter--;
  148.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  149.                 var newText = new Array();
  150.                 newText[counter] = document.createElement(" ");
  151.                 var newTextNode = document.createTextNode(textOption);
  152.                 newText[counter].appendChild(newTextNode);
  153.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  154.             }
  155.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  156.             newGraf.appendChild(clone);    
  157.             nodeChangingArea.appendChild(newGraf);
  158.             nodeChangingArea.insertBefore(newGraf,oldGraf);
  159.         }else{alert("You didn't created an option !!!");}
  160.     }else{alert("You didn't created an question !!!");}
  161. }
  162.  
  163. function replaceNode() {
  164.     var inChoice = document.getElementById("grafCount").selectedIndex;
  165.     var inText = document.getElementById("textArea").value;
  166.     if(inText != 0){ 
  167.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){
  168.             var newText = document.createTextNode(inText);
  169.             var newGraf = document.createElement("pre");
  170.             newGraf.appendChild(newText);
  171.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  172.             var oldGraf = allGrafs.item(inChoice);
  173.             clone = nodeChangingRadio.cloneNode(true);
  174.             clone.id = "clone";
  175.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
  176.             while(counter!=0){
  177.                 counter--;
  178.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  179.                 var newText = new Array();
  180.                 newText[counter] = document.createElement(" ");
  181.                 var newTextNode = document.createTextNode(textOption);
  182.                 newText[counter].appendChild(newTextNode);
  183.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  184.             }
  185.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  186.             newGraf.appendChild(clone);    
  187.             nodeChangingArea.appendChild(newGraf);
  188.             nodeChangingArea.replaceChild(newGraf,oldGraf);
  189.         }else{alert("You didn't created an option !!!");}
  190.     }else{alert("You didn't created an question !!!");}
  191. }
  192.  
  193. function nodeChanger()  {
  194.     var actionType = -1;
  195.     var currentPgraphCount = document.getElementsByTagName("pre").length;
  196.     var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
  197.     for (var i=0; i<radioButtonSet.length; i++) {
  198.         if (radioButtonSet[i].checked) {
  199.             actionType = i;
  200.         }
  201.     }
  202.     switch(actionType) {
  203.         case 0:
  204.             addNode();
  205.             break;
  206.         case 1:
  207.             if (currentPgraphCount > 0) {
  208.                 delNode();
  209.                 break;
  210.             }
  211.         case 2:
  212.             if (currentPgraphCount > 0) {
  213.                 insertNode();
  214.                 break;
  215.             }
  216.         case 3:
  217.             if (currentPgraphCount > 0) {
  218.                 replaceNode();
  219.                 break
  220.             }
  221.         default:
  222.             alert("Nenhuma opção foi escolhida !");
  223.     }
  224.     document.getElementById("grafCount").options.length = 0;
  225.     for (i=0; i<nodeChangingArea.getElementsByTagName("pre").length; i++) {
  226.         document.getElementById("grafCount").options[i] = new Option(i+1);
  227.     }
  228.     return false;
  229. }
  230.  
  231.  


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.
Jan 30 '10 #9

P: 26
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.
Expand|Select|Wrap|Line Numbers
  1.     var inRadio = document.getElementById("radioButtons").value;
  2.     var inRadio2 = parseInt(inRadio);
  3.             if ( isNaN( inRadio ) || inRadio2 == " "  ){ ... }
  4.             if ( ! isNaN( inRadio ) && inRadio2  > 1 ){ ... }
  5.  
  6.  
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).
Jan 30 '10 #10

Dormilich
Expert Mod 5K+
P: 8,639
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)
Jan 30 '10 #11

P: 26
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

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

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 ?
Jan 30 '10 #12

Dormilich
Expert Mod 5K+
P: 8,639
you mean the cols and rows attributes?
Jan 30 '10 #13

P: 26
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.
Jan 30 '10 #14

gits
Expert Mod 5K+
P: 5,390
hmmm ... so you want to force the manual linebreaks to a 'html'-linebreak?

you might do that with a replace() like:
Expand|Select|Wrap|Line Numbers
  1. var myHtmlText = textAreaText.replace(/\n/g, '<br/>');
kind regards
Jan 31 '10 #15

gits
Expert Mod 5K+
P: 5,390
ahh - and one more note: in your posted code the switch-statement:

Expand|Select|Wrap|Line Numbers
  1.  
  2. switch(actionType) {
  3.     case 0:
  4.         addNode();
  5.         break;
  6.     case 1:
  7.         if (currentPgraphCount > 0) {
  8.             delNode();
  9.             break;
  10.         }
  11.     case 2:
  12.         if (currentPgraphCount > 0) {
  13.             insertNode();
  14.             break;
  15.         }
  16.     case 3:
  17.         if (currentPgraphCount > 0) {
  18.             replaceNode();
  19.             break
  20.         }
  21.     default:
  22.         alert("Nenhuma opção foi escolhida !");
  23. }
  24.  
is wrong ... it should look like:
Expand|Select|Wrap|Line Numbers
  1. switch( actionType ) {
  2.     case 0:
  3.         addNode();
  4.         break;
  5.     case 1:
  6.         if (currentPgraphCount > 0) {
  7.             delNode();
  8.         }
  9.         break;
  10.     case 2:
  11.         if (currentPgraphCount > 0) {
  12.             insertNode();
  13.         }
  14.         break;
  15.     case 3:
  16.         if (currentPgraphCount > 0) {
  17.             replaceNode();
  18.         }
  19.         break;
  20.     default:
  21.         alert("Nenhuma opção foi escolhida !");
  22.         break;
  23. }
  24.  
Jan 31 '10 #16

P: 26
Oh, the last break and breaks outside the curve parentesis ( { } ), will fix that. Thank You.
Jan 31 '10 #17

gits
Expert Mod 5K+
P: 5,390
:) and does the replace work for your linebreak issue?
Jan 31 '10 #18

P: 26
Sadly no, i have been googling and found several solutions.
1st using a counter for words. Spliting at a certain count and inserting an enter.
2nd using the tag <wbr> but fails due to the use of <pre> to ensure the whole format of the text inserted by a user.

The script is working, but besides the problem with breaking the line, in firefox the answer for multiple choice ain't showing. Opera and IE8 working fine.
Gonna make my own solution perhaps doing the same what others did, i'm running out of ideas on this one. Breaking the lines by counting words maybe be the best way t do it. Avoids tempering too much with the remaining code.
Jan 31 '10 #19

P: 26
Well have found the problem with firefox, had to redesign the function and works well know, for all browser.

I need to be more carefull when dealing with dynamic spaces since firefox doesn't deal well with dynamic vars.
Feb 1 '10 #20

acoder
Expert Mod 15k+
P: 16,027
Perhaps you could post your working code for the benefit of others.

The reason why the line break isn't working is because you're using the <pre> tag which will just print out the <br> tag rather than actually force a line break.
Feb 2 '10 #21

P: 26
Hello.
As soon i defend my work i will post the entire code to alls benefit. Just give me some time.
I'm truly sorry, but in my faculty they search the code for any similarities in the web, so must be certain they will see that i have ask for help but the working project is due to my efforts, and not somebody else.
But i like to share, and when i doo it will al in english plus the comments where tricky parts are.

Thanks to community for all the help and insights.
Feb 2 '10 #22

P: 26
I have already another assignment so therefore remember to post the code.

HTML:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4.     <title>Multiple Questions Form</title>
  5.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  6.     <script type="text/javascript" src="script.js">
  7.     <*link rel="stylesheet" type="text/css" href="style.css">
  8.     </script>
  9. </head>
  10. <body>
  11.     <form action="#">
  12.  
  13.         <p align="center">Multiple Question Form</p>
  14.         <fieldset type="">
  15.         <legend><i>Question:</i></legend>
  16.  
  17.         <p>&nbsp;&nbsp;&nbsp;&nbsp;<textarea id="textArea" rows="5" cols="145"></textarea></p>
  18.  
  19.         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Number of options to answer (default = 4) :
  20.         &nbsp;&nbsp;<input type="text" size=2 name="Radio" id="radioButtons"/></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  21.         <input type="button" value="Create options" id="criarOpcoes" style="background-color:#0000FF; color: #ffffff;" onClick="addRadioButtons();" />
  22.         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  23.         <input type="button" value="Reset Options" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
  24.  
  25.         <div id="radioButtonsChoice"><br/></div><br/>
  26.  
  27.         <p>
  28.         &nbsp;&nbsp;&nbsp;<label><input type="radio" name="nodeAction" />Add Question</label>
  29.         <label><input type="radio" name="nodeAction" />Erase Question</label>
  30.         <label><input type="radio" name="nodeAction" />Insert before an question</label>
  31.         <label><input type="radio" name="nodeAction" />Replace Question</label>
  32.         </p>            
  33.  
  34.         <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Question # </label><select type="" id="grafCount"> </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  35.         <input type="submit" value="Perform action!" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  36.         <input type="reset" value="Clean Fields" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  37.         <input type="button" value="Clean Fields and options" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
  38.         <p/>
  39.         <p style ="text-align:center"><b><i>Portugal 2010</i></b></p>
  40.         </fieldset>
  41.     </form>
  42.     <div id="questionario"></div>
  43. </body>
  44. </html>
  45.  
  46.  
Script:

Expand|Select|Wrap|Line Numbers
  1. window.onload = initAll;
  2. var nodeChangingArea;
  3. var nodeChangingRadio;
  4. var counter;
  5.  
  6. function initAll() {
  7.     document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
  8.     nodeChangingArea = document.getElementById("questionario");
  9.     nodeChangingRadio = document.getElementById("radioButtonsChoice");
  10. }
  11.  
  12. function addRadioButtons() {
  13.     var inRadio = document.getElementById("radioButtons").value;
  14.     var inRadio2 = parseInt(inRadio);
  15.     var newChoice = document.createElement("form");
  16.     if(inRadio != 0){
  17.         if(isNaN(inRadio) || inRadio2 == " " ){
  18.             if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
  19.                 for (var h=0; h<4; h++){
  20.                     var newBox = document.createElement("input");
  21.                     newBox.setAttribute("type","checkbox");//newBox.type = "checkbox";
  22.                     newBox.setAttribute("id" , "Box");
  23.                     var newAnswer = document.createElement("textarea");
  24.                     newAnswer.setAttribute("id","Answer");
  25.                     newAnswer.setAttribute("rows","1");
  26.                     newAnswer.setAttribute("cols","100");
  27.                     var separateAnswer = document.createElement("br");
  28.                     newChoice.appendChild(separateAnswer);                        
  29.                     newChoice.appendChild(newBox);                                    
  30.                     newChoice.appendChild(newAnswer);                                
  31.                 }
  32.                 nodeChangingRadio.appendChild(newChoice);
  33.             }else{alert("Apague as opções existentes e crie novas !");}
  34.             return(false);
  35.         }
  36.         if(inRadio != ""){
  37.             if( !isNaN(inRadio) && inRadio2 > 1 ){
  38.                 if(!nodeChangingRadio.lastChild.hasChildNodes() || nodeChangingRadio.firstChild.hasChildNodes() ){
  39.                     for(var l=0; l < inRadio ; l++){
  40.                         var newBox = document.createElement("input");
  41.                         newBox.setAttribute("type","checkbox");//newBox.type = "checkbox";
  42.                         newBox.setAttribute("id","Box");//newBox.id = "Box";
  43.                         var newAnswer = document.createElement("textarea");
  44.                         newAnswer.setAttribute("id","Answer");
  45.                         newAnswer.setAttribute("rows","1");
  46.                         newAnswer.setAttribute("cols","100");
  47.                         var separateAnswer = document.createElement("br");
  48.                         newChoice.appendChild(separateAnswer);
  49.                         newChoice.appendChild(newBox);
  50.                         newChoice.appendChild(newAnswer);
  51.                     }
  52.                     nodeChangingRadio.appendChild(newChoice);
  53.                 }else{alert("Apague as opções existentes e crie novas !");}
  54.             }else{alert("Número de opções inseridas é insuficiente ou número inválido !");}
  55.         }
  56.     }else{
  57.         alert("Não inseriu um número de opções !");
  58.     }
  59.  
  60. }
  61.  
  62. function delNode() {
  63.     var delChoice = document.getElementById("grafCount").selectedIndex;
  64.     var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  65.     var killGraf = allGrafs.item(delChoice);
  66.     nodeChangingArea.removeChild(killGraf);
  67. }
  68.  
  69. function addNode() {
  70.     var inText = document.getElementById("textArea").value;
  71.     if(inText.length != 0){
  72.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){
  73.  
  74.             var newText = document.createTextNode(inText);
  75.  
  76.  
  77.             //var newGraf = document.createElement("pre");//pre or wbr
  78.  
  79.             // DIV
  80.             //alert(nodeChangingRadio.childNodes[0].tagName); // BR
  81.             //alert(nodeChangingRadio.childNodes[1].tagName); // FORM
  82.             //alert(nodeChangingRadio.childNodes[1].childNodes[0].tagName); // BR    -------- > No caso de 2 opções criadas com o conteúdo de 1 e 2
  83.             //alert(nodeChangingRadio.childNodes[1].childNodes[1].tagName); // INPUT
  84.             //alert(nodeChangingRadio.childNodes[1].childNodes[2].tagName); // textarea
  85.             //alert(nodeChangingRadio.childNodes[1].childNodes[2].nodeType); // -> 1 Element_Node
  86.             //alert(nodeChangingRadio.childNodes[1].childNodes[2].childNodes[0].nodeType); // -> 3 Text_Node
  87.             //alert(nodeChangingRadio.childNodes[1].childNodes[3].tagName); // BR
  88.             //alert(nodeChangingRadio.childNodes[1].childNodes[4].tagName); // INPUT
  89.             //alert(nodeChangingRadio.childNodes[1].childNodes[5].tagName); // textarea
  90.  
  91.             var browser = navigator.appName;
  92.             var b_version = navigator.appVersion;
  93.             var version = parseFloat(b_version);
  94.  
  95.             alert("O seu browser é o: " + browser);
  96.  
  97.  
  98.  
  99.  
  100.             var newGraf = document.createElement("pre");
  101.             newGraf.appendChild(newText);
  102.             clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
  103.             counter = nodeChangingRadio.childNodes[1].getElementsByTagName("textarea").length;
  104.             for (var h = 0; h < nodeChangingRadio.childNodes[1].getElementsByTagName("textarea").length ; h++ ){
  105.                 counter--;
  106.                 var textOption = nodeChangingRadio.getElementsByTagName("textarea")[counter].value;//var textOption = nodeChangingRadio.getElementsByTagName("textarea")[counter].value;
  107.                 var newText1 = document.createElement("span");
  108.                 //var newTextNode = new Array();
  109.                 newTextNode = document.createTextNode(textOption);//newTextNode[counter] = document.createTextNode(textOption);
  110.                 newText1.appendChild(newTextNode);//newText1.appendChild(newTextNode[counter]);
  111.                 //clone.appendChild(newText1);
  112.                 //clone.childNodes[1].removeChild(clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  113.                 clone.childNodes[1].replaceChild(newText1 , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  114.                 //clone.childNodes[1].appendChild(newText1)
  115.             }
  116.             newGraf.appendChild(clone);
  117.             nodeChangingArea.appendChild(newGraf);
  118.         }else{alert("Não criou nenhuma opção !!!");}
  119.     }else{alert("Não criou uma pergunta !!!");}
  120. }
  121.  
  122. function clearForm(oForm){    // Removed from the web, just to be possible clear the forms plus the options at the same time.                                                    
  123.   var elements = oForm.elements;                                                 
  124.   oForm.reset();
  125.   resetOpcoes();                                                                 
  126.   for(i=0; i<elements.length; i++) {
  127.     if(elements[i].type != null){
  128.         field_type = elements[i].type.toLowerCase();
  129.         switch(field_type) {
  130.             case "text": 
  131.             case "password": 
  132.             case "textarea":
  133.             case "hidden":    
  134.                 elements[i].value = ""; 
  135.                 break;
  136.             case "radio":
  137.             case "checkbox":
  138.                 if (elements[i].checked) {
  139.                     elements[i].checked = false; 
  140.                 }
  141.                 break;
  142.             case "select-one":
  143.             case "select-multi":
  144.                 elements[i].selectedIndex = -1;
  145.                 break;
  146.             default: 
  147.                 break;
  148.             }
  149.         }    
  150.     }
  151. }
  152.  
  153. function resetOpcoes(){
  154.     if (nodeChangingRadio && nodeChangingRadio.hasChildNodes && nodeChangingRadio.removeChild) {
  155.         while (nodeChangingRadio.lastChild.hasChildNodes()) {    // while (nodeChangingRadio.lastChild.hasChildNodes()) {                                    
  156.             nodeChangingRadio.removeChild(nodeChangingRadio.lastChild);                            
  157.         }
  158.     }
  159. }
  160.  
  161. function insertNode() {
  162.     var inChoice = document.getElementById("grafCount").selectedIndex;
  163.     var inText = document.getElementById("textArea").value;
  164.     if(inText != 0){ 
  165.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){        
  166.             var newText = document.createTextNode(inText);
  167.             var newGraf = document.createElement("pre");
  168.             newGraf.appendChild(newText);
  169.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  170.             var oldGraf = allGrafs.item(inChoice);
  171.             clone = nodeChangingRadio.cloneNode(true);
  172.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;        
  173.             /*
  174.             while(counter!=0){
  175.                 counter--;
  176.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  177.                 var newText = new Array();
  178.                 newText[counter] = document.createElement(" ");
  179.                 var newTextNode = document.createTextNode(textOption);
  180.                 newText[counter].appendChild(newTextNode);
  181.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  182.             }
  183.             */
  184.             while(counter!=0){
  185.                 counter--;
  186.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  187.                 newText = document.createElement(" ");
  188.                 var newTextNode = document.createTextNode(textOption);
  189.                 newText.appendChild(newTextNode);
  190.                 clone.childNodes[1].replaceChild(newText , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  191.             }
  192.             newGraf.appendChild(clone);    
  193.             nodeChangingArea.appendChild(newGraf);
  194.             nodeChangingArea.insertBefore(newGraf,oldGraf);
  195.         }else{alert("Não criou nenhuma opção !!!");}
  196.     }else{alert("Não inseriu uma pergunta !!!");}
  197. }
  198.  
  199. function replaceNode() {
  200.     var inChoice = document.getElementById("grafCount").selectedIndex;
  201.     var inText = document.getElementById("textArea").value;
  202.     if(inText != 0){ 
  203.         if(nodeChangingRadio.lastChild.hasChildNodes(false)){
  204.             var newText = document.createTextNode(inText);
  205.             var newGraf = document.createElement("pre");
  206.             newGraf.appendChild(newText);
  207.             var allGrafs = nodeChangingArea.getElementsByTagName("pre");
  208.             var oldGraf = allGrafs.item(inChoice);
  209.             clone = nodeChangingRadio.cloneNode(true);
  210.             clone.id = "clone";
  211.             counter = clone.childNodes[1].getElementsByTagName("textarea").length;
  212.             /*
  213.             while(counter!=0){
  214.                 counter--;
  215.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  216.                 var newText = new Array();
  217.                 newText[counter] = document.createElement(" ");
  218.                 var newTextNode = document.createTextNode(textOption);
  219.                 newText[counter].appendChild(newTextNode);
  220.                 clone.childNodes[1].replaceChild(newText[counter] , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  221.             }
  222.             */
  223.             while(counter!=0){
  224.                 counter--;
  225.                 var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
  226.                 newText = document.createElement(" ");
  227.                 var newTextNode = document.createTextNode(textOption);
  228.                 newText.appendChild(newTextNode);
  229.                 clone.childNodes[1].replaceChild(newText , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
  230.             }
  231.             clone.childNodes[1].removeChild(clone.childNodes[1].childNodes[0]);
  232.             newGraf.appendChild(clone);    
  233.             nodeChangingArea.appendChild(newGraf);
  234.             nodeChangingArea.replaceChild(newGraf,oldGraf);
  235.         }else{alert("Não criou nenhuma opção !!!");}
  236.     }else{alert("Não inseriu uma pergunta !!!");}
  237. }
  238.  
  239. function nodeChanger()  {
  240.     var actionType = -1;
  241.     var currentPgraphCount = document.getElementsByTagName("pre").length;
  242.     var radioButtonSet = document.getElementsByTagName("form")[0].nodeAction;
  243.     for (var i=0; i<radioButtonSet.length; i++) {
  244.         if (radioButtonSet[i].checked) {
  245.             actionType = i;
  246.         }
  247.     }
  248.     switch(actionType) {
  249.         case 0:
  250.             addNode();
  251.             break;
  252.         case 1:
  253.             if (currentPgraphCount > 0) {
  254.                 delNode();
  255.             }
  256.             break;
  257.         case 2:
  258.             if (currentPgraphCount > 0) {
  259.                 insertNode();
  260.             }
  261.             break;
  262.         case 3:
  263.             if (currentPgraphCount > 0) {
  264.                 replaceNode();
  265.             }
  266.             break;
  267.         default:
  268.             alert("Nenhuma opção foi escolhida !");
  269.             break;
  270.     }
  271.     document.getElementById("grafCount").options.length = 0;
  272.     for (i=0; i<nodeChangingArea.getElementsByTagName("pre").length; i++) {
  273.         document.getElementById("grafCount").options[i] = new Option(i+1);
  274.     }
  275.     return false;
  276. }
  277.  
  278.  
Notes: I kept the alerts and all, since they will help anyone who use this code to find out the DOM Tree and how each element is placed. Very helpfull if you wanna add / remove / edit childs in the tree.

By the way, you can create dinamic spaces by two ways with span and div, i have tested them both. Have no idea whats the advantage, but just in case left this alternative.

Only thing missing is still fit the text from answers and questions in the page without prolonguing them. But a "cheap alternative" is to use the tag "wbr" instead of "pre". Which is more common since it is made to direct and simple questions / answers and not built with paragrafs or rimes or something like that.

Working: IE8 / FF / Opera
Feb 6 '10 #23

acoder
Expert Mod 15k+
P: 16,027
Thanks for posting and sharing your code. If posting was going to be a problem, perhaps an indication as to what the problem and solution was in Firefox probably would've sufficed.
Feb 7 '10 #24

Post your reply

Sign in to post your reply or Sign up for a free account.