Javascript Erase all Nodes at once.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #16
    ahh - and one more note: in your posted code the switch-statement:

    Code:
        
    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 !");
    }
    is wrong ... it should look like:
    Code:
    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 !");
            break;
    }

    Comment

    • NKTA
      New Member
      • Jan 2010
      • 26

      #17
      Oh, the last break and breaks outside the curve parentesis ( { } ), will fix that. Thank You.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #18
        :) and does the replace work for your linebreak issue?

        Comment

        • NKTA
          New Member
          • Jan 2010
          • 26

          #19
          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.

          Comment

          • NKTA
            New Member
            • Jan 2010
            • 26

            #20
            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.

            Comment

            • acoder
              Recognized Expert MVP
              • Nov 2006
              • 16032

              #21
              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.

              Comment

              • NKTA
                New Member
                • Jan 2010
                • 26

                #22
                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.

                Comment

                • NKTA
                  New Member
                  • Jan 2010
                  • 26

                  #23
                  I have already another assignment so therefore remember to post the code.

                  HTML:

                  Code:
                  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                  <html>
                  <head>
                  	<title>Multiple Questions 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><i>Question:</i></legend>
                  	
                  		<p>&nbsp;&nbsp;&nbsp;&nbsp;<textarea id="textArea" rows="5" cols="145"></textarea></p>
                  		
                  		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Number of options to answer (default = 4) :
                  		&nbsp;&nbsp;<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="Reset Options" id="resetOpcoesCriadas" style="background-color:#cc0000; color: #ffffff;" onClick="resetOpcoes();"/><br/>
                  		
                  		<div id="radioButtonsChoice"><br/></div><br/>
                  			
                  		<p>
                  		&nbsp;&nbsp;&nbsp;<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 an question</label>
                  		<label><input type="radio" name="nodeAction" />Replace Question</label>
                  		</p>			
                  
                  		<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>Question # </label><select type="" id="grafCount"> </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  		<input type="submit" value="Perform action!" style="background-color:#ffffff; color: #cc0000"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  		<input type="reset" value="Clean Fields" id="resetCampos" style="background-color:#cc0000; color: #ffffff;"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  		<input type="button" value="Clean Fields and options" name="clear" id="resetCampos" style="background-color:#cc0000; color: #ffffff;" onClick="clearForm(this.form);"/></p>
                  		<p/>
                  		<p style ="text-align:center"><b><i>Portugal 2010</i></b></p>
                  		</fieldset>
                  	</form>
                  	<div id="questionario"></div>
                  </body>
                  </html>
                  Script:

                  Code:
                  window.onload = initAll;
                  var nodeChangingArea;
                  var nodeChangingRadio;
                  var counter;
                  
                  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 inRadio2 = parseInt(inRadio);
                  	var newChoice = document.createElement("form");
                  	if(inRadio != 0){
                  		if(isNaN(inRadio) || inRadio2 == " " ){
                  			if(!nodeChangingRadio.lastChild.hasChildNodes()|| nodeChangingRadio.firstChild.hasChildNodes()){
                  				for (var h=0; h<4; h++){
                  					var newBox = document.createElement("input");
                  					newBox.setAttribute("type","checkbox");//newBox.type = "checkbox";
                  					newBox.setAttribute("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) && inRadio2 > 1 ){
                  				if(!nodeChangingRadio.lastChild.hasChildNodes() || nodeChangingRadio.firstChild.hasChildNodes() ){
                  					for(var l=0; l < inRadio ; l++){
                  						var newBox = document.createElement("input");
                  						newBox.setAttribute("type","checkbox");//newBox.type = "checkbox";
                  						newBox.setAttribute("id","Box");//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;
                  	if(inText.length != 0){
                  		if(nodeChangingRadio.lastChild.hasChildNodes(false)){
                  		
                  			var newText = document.createTextNode(inText);
                  			
                  			
                  			//var newGraf = document.createElement("pre");//pre or wbr
                  					
                  			// DIV
                  			//alert(nodeChangingRadio.childNodes[0].tagName); // BR
                  			//alert(nodeChangingRadio.childNodes[1].tagName); // FORM
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[0].tagName); // BR    -------- > No caso de 2 opções criadas com o conteúdo de 1 e 2
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[1].tagName); // INPUT
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[2].tagName); // textarea
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[2].nodeType); // -> 1 Element_Node
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[2].childNodes[0].nodeType); // -> 3 Text_Node
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[3].tagName); // BR
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[4].tagName); // INPUT
                  			//alert(nodeChangingRadio.childNodes[1].childNodes[5].tagName); // textarea
                  			
                  			var browser = navigator.appName;
                  			var b_version = navigator.appVersion;
                  			var version = parseFloat(b_version);
                  			
                  			alert("O seu browser é o: " + browser);
                  			
                  			
                  
                  			
                  			var newGraf = document.createElement("pre");
                  			newGraf.appendChild(newText);
                  			clone = document.getElementById("radioButtonsChoice").cloneNode(true);//var clone = nodeChangingRadio.cloneNode(true);
                  			counter = nodeChangingRadio.childNodes[1].getElementsByTagName("textarea").length;
                  			for (var h = 0; h < nodeChangingRadio.childNodes[1].getElementsByTagName("textarea").length ; h++ ){
                  				counter--;
                  				var textOption = nodeChangingRadio.getElementsByTagName("textarea")[counter].value;//var textOption = nodeChangingRadio.getElementsByTagName("textarea")[counter].value;
                  				var newText1 = document.createElement("span");
                  				//var newTextNode = new Array();
                  				newTextNode = document.createTextNode(textOption);//newTextNode[counter] = document.createTextNode(textOption);
                  				newText1.appendChild(newTextNode);//newText1.appendChild(newTextNode[counter]);
                  				//clone.appendChild(newText1);
                  				//clone.childNodes[1].removeChild(clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                  				clone.childNodes[1].replaceChild(newText1 , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                  				//clone.childNodes[1].appendChild(newText1)
                  			}
                  			newGraf.appendChild(clone);
                  			nodeChangingArea.appendChild(newGraf);
                  		}else{alert("Não criou nenhuma opção !!!");}
                  	}else{alert("Não criou uma pergunta !!!");}
                  }
                  
                  function clearForm(oForm){	// Removed from the web, just to be possible clear the forms plus the options at the same time.													
                    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);
                  			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]);
                  			}
                  			*/
                  			while(counter!=0){
                  				counter--;
                  				var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
                  				newText = document.createElement(" ");
                  				var newTextNode = document.createTextNode(textOption);
                  				newText.appendChild(newTextNode);
                  				clone.childNodes[1].replaceChild(newText , clone.childNodes[1].getElementsByTagName("textarea")[counter]);
                  			}
                  			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]);
                  			}
                  			*/
                  			while(counter!=0){
                  				counter--;
                  				var textOption = clone.childNodes[1].getElementsByTagName("textarea")[counter].value;
                  				newText = document.createElement(" ");
                  				var newTextNode = document.createTextNode(textOption);
                  				newText.appendChild(newTextNode);
                  				clone.childNodes[1].replaceChild(newText , 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 !");
                  			break;
                  	}
                  	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;
                  }
                  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

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #24
                    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.

                    Comment

                    Working...