Solved

modify javascript toggle to swap two divs back and forth

Posted on 2010-08-30
8
742 Views
Last Modified: 2013-12-13
Back in January, Expert Kadaba provided an excellent solution to my javascript question. But now the needs have changed again, slightly, and I want to ask, can Kadaba, or another expert help?

See related question for background.

Previously, when user clicked a button, the script would remove the default div of info and replace it with a new div of info. But now I want to apply the behavior to a check box. So when the user checks the check box the divs swap. But if the user unchecks the checkbox, the divs should be swapped back.

Hope this makes sense.

The previous solution is attached.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript - Extending forms</title>
<!-- FROM QUIRKSMODE -->
<script type="text/javascript">
<!--
var divAdded = new Array(); 
var divCount = 0;
function moreFields(nodeToClone) {
	var newFields = document.getElementById(nodeToClone).cloneNode(true);
	newFields.id = 'div_'+divCount;
	divAdded[divCount] = 'div_'+divCount;
	newFields.style.display = 'block';
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
	divCount++;
}

function removeFields(){
	for(var i=0;i<divAdded.length;i++){
		if(document.getElementById(divAdded[i])){
			document.forms[0].removeChild(document.getElementById(divAdded[i]));
		}
	}
	moreFields('newreadroot');
}
window.onload = function(){
	moreFields('readroot');
};

 
// -->
</script>
</head>
 
<body>
 
<h3>Example</h3>
 
<form id="request" action="" method="post">

<div style="border:thick dashed #6699CC;margin:10px;padding:10px;width:500px">
 <div class="buttons">


<button type="button" id="removeAll" onclick="removeFields();" value="Remove new Fields added" class="positive">
<img src="add.png" />
I will pick up my transcripts
</button>
</div class="buttons">
</div>

<div id="readroot" style="display:none">
<input type="button" value="Remove transcript destination" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" src="delete.png" alt="Remove transcript destination"/>
<br />
 

<label for="HowMany">Number of transcripts to be sent to this address</label>:
<br />
<input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>
<br />
 
<label for="Name">Name</label>
<br />
<input name="Name[]" id="Name" class="required" title="Enter the name" maxlength="25"/>
<br />
 
<label for="DCity">City</label>
<br />
<input name="DCity[]" id="DCity" class="required" title="Enter your City" maxlength=""/>
<br />
 
<label for="Timing">When Should the transcript be sent?</label>
<br />
 
<select id="Timing" name="Timing[]"  class="validate-selection">
<option value="X">Select</option>
<option value="1">Now</option>
<option value="2">When semester grades are posted</option>
<option value="3">When degree statement is posted</option>
</select>
</div id="readroot">

<div id="newreadroot" style="display:none;">
<input type="hidden" name="self" value="1" />

<input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>Number of Transcripts
</div>

 
<span id="writeroot"></span id="writeroot">
<br> 
<div class="buttons">
<button type="button" id="btnMore" onClick="moreFields('readroot');" value="Add another transcript destination" class="positive">
<img src="add.png" />
Add another transcript destination
</button>
 
<button type="submit" class="positive">
<img src="bullet_go.png" />
Submit Completed Form
</button>


</div class="buttons">
</form>
 
</body>
</html>

Open in new window

0
Comment
Question by:aberns
  • 3
  • 3
  • 2
8 Comments
 
LVL 6

Expert Comment

by:Ludwig Diehl
ID: 33562172
Hello, it's basically the same you should only change the type of element. However the behavior will be a little strange specially when adding nodes... you will see...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Javascript - Extending forms</title>
        <!-- FROM QUIRKSMODE -->
        <script type="text/javascript">
        <!--
        var divAdded = new Array(); 
        var divCount = 0;
        function moreFields(nodeToClone) {
        	var newFields = document.getElementById(nodeToClone).cloneNode(true);
        	newFields.id = 'div_'+divCount;
        	divAdded[divCount] = 'div_'+divCount;
        	newFields.style.display = 'block';
        	var insertHere = document.getElementById('writeroot');
        	insertHere.parentNode.insertBefore(newFields,insertHere);
        	divCount++;
        }
        
        function removeFields(){
        	for(var i=0;i<divAdded.length;i++){
        		if(document.getElementById(divAdded[i])){
        			document.forms[0].removeChild(document.getElementById(divAdded[i]));
        		}
        	}
        	moreFields('newreadroot');
        }
        window.onload = function(){
        	moreFields('readroot');
        };
        
         
        // -->
        </script>
    </head> 
    <body>
        <h3>Example</h3>
        <form id="request" action="" method="post">
            <div style="border:thick dashed #6699CC;margin:10px;padding:10px;width:500px">
                <div class="buttons">                 
                     <input type="checkbox" id="removeAll" onclick="removeFields();" class="positive" />
                     I will pick up my transcripts
                </div>
            </div>
            <div id="readroot" style="display:none">
                <input type="checkbox" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" src="delete.png" alt="Remove transcript destination"/>
                Remove transcript destination                
                <br />
                <label for="HowMany">Number of transcripts to be sent to this address</label>:
                <br />
                <input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>
                <br />
                <label for="Name">Name</label>
                <br />
                <input name="Name[]" id="Name" class="required" title="Enter the name" maxlength="25"/>
                <br /> 
                <label for="DCity">City</label>
                <br />
                <input name="DCity[]" id="DCity" class="required" title="Enter your City" maxlength=""/>
                <br />
                <label for="Timing">When Should the transcript be sent?</label>
                <br />
                <select id="Timing" name="Timing[]"  class="validate-selection">
                    <option value="X">Select</option>
                    <option value="1">Now</option>
                    <option value="2">When semester grades are posted</option>
                    <option value="3">When degree statement is posted</option>
                </select>
            </div>
            <div id="newreadroot" style="display:none;">
                <input type="hidden" name="self" value="1" />
                <input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>Number of Transcripts
            </div>
            <span id="writeroot"></span>
            <br /> 
            <div class="buttons">
                <input type="checkbox" id="btnMore" onclick="moreFields('readroot');" class="positive" />
                Add another transcript destination                
                <button type="submit" class="positive">
                    <img src="bullet_go.png" />
                    Submit Completed Form
                </button>
            </div>
        </form>
     </body>
</html>

Open in new window

0
 
LVL 6

Expert Comment

by:Ludwig Diehl
ID: 33562244
luckily the onclick event matches the requested behavior however you could add this validation on the onclick event:


onclick="if(this.checked) removeFields();"

onclick="if(this.checked) this.parentNode.parentNode.removeChild(this.parentNode);"

onclick="if(this.checked){ this.checked=false;moreFields('readroot');}" //I added this.checked=false so everytime you click the next checkbox appears unchecked

0
 

Author Comment

by:aberns
ID: 33579931
To clarify, really what I want is this.

Currently, when you check this checkbox removeall, it calls onclick="removeFields();"

That is great. However, if a user unchecks the checkbox, what I would like to happen is that the div newreadroot disappears, and the original div readroot reappears.

So you could toggle back and forth if you were a user and accidentally clicked "removeall".

0
 
LVL 22

Expert Comment

by:kadaba
ID: 33580067
I took the previous example of mine and worked on it..
check if this is what you were looking for..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript - Extending forms</title>
<!-- FROM QUIRKSMODE -->
<script type="text/javascript">
<!--
var divAdded = new Array(); 
var divCount = 0;

function moreFields(nodeToClone, isReplace) 
{
	var newFields = document.getElementById(nodeToClone).cloneNode(true);
		
	if(isReplace)
	{
		cloneInfo(nodeToClone,'div_newcontent');
	}
	else
	{
		cloneInfo(nodeToClone,'div_'+divCount);
		divAdded[divCount] = 'div_'+divCount;
		divCount++;	
	}	
}

var removedDiv = new Array();

function removeFields(chkObj){
	if(chkObj.checked)
	{
		removedDiv = divAdded;
		for(var i=0;i<divAdded.length;i++){
			if(document.getElementById(divAdded[i])){
				document.forms[0].removeChild(document.getElementById(divAdded[i]));
			}
		}
		divCount = 0;
		divAdded=null;
		moreFields('newreadroot',true);
	}
	else
	{
		document.forms[0].removeChild(document.getElementById('div_newcontent'));
		divAdded = removedDiv;
		for(var i=0;i<divAdded.length;i++)
		{
			cloneInfo('readroot',divAdded[i]);
			divCount++;
		}
		removedDiv = null;
	}	
}

function cloneInfo(nodeToClone,id) 
{
	var newFields = document.getElementById(nodeToClone).cloneNode(true);
	newFields.id = id;
	newFields.style.display = 'block';
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

function removeFromFieldsArray(val)
{	var index;
	var temp = new Array();
	for(var i=0;i<divAdded.length;i++)
	{
		if(divAdded[i] != val)
		{
			temp[temp.length] = divAdded[i];
		}
	}
	divAdded = temp;
}

window.onload = function(){
	moreFields('readroot',false);
};

 
// -->
</script>
</head>
 
<body>
 
<h3>Example</h3>
 
<form id="request" action="" method="post">
<div id="readroot" style="display:none">
<input type="button" value="Remove transcript destination" onclick="this.parentNode.parentNode.removeChild(this.parentNode);removeFromFieldsArray(this.parentNode.id)" src="delete.png" alt="Remove transcript destination"/>
<br />
 
<label for="HowMany">Number of transcripts to be sent to this address</label>:
<br />
<input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>
<br />
 
<label for="Name">Name</label>
<br />
<input name="Name[]" id="Name" class="required" title="Enter the name" maxlength="25"/>
<br />
 
<label for="DCity">City</label>
<br />
<input name="DCity[]" id="DCity" class="required" title="Enter your City" maxlength=""/>
<br />
 
<label for="Timing">When Should the transcript be sent?</label>
<br />
 
<select id="Timing" name="Timing[]"  class="validate-selection">
<option value="X">Select</option>
<option value="1">Now</option>
<option value="2">When semester grades are posted</option>
<option value="3">When degree statement is posted</option>
</select>
</div id="readroot">

<div id="newreadroot" style="display:none;border:1px solid black;width:650px">
This is where the new content will be added.<br>
Sample Text: <input type="text" id="newText"><br>
Sample Radios:<input type="radio" id="rad1" name="radGrp"> 1 <input type="radio" id="rad2" name="radGrp">2<br>
Sample select:
<select id="ddsel">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">4</option>
</select>
<br>
Sample check box: <input type="checkbox" id="chkbx"><br>
</div>

 
<span id="writeroot"></span id="writeroot">
<br> 
<div class="buttons">
<button type="button" id="btnMore" onClick="moreFields('readroot',false);" value="Add another transcript destination" class="positive">
<img src="add.png" />
Add another transcript destination
</button>
 
<button type="submit" class="positive">
<img src="bullet_go.png" />
Submit Completed Form
</button>

<button type="button" id="removeAll" onclick="removeFields();" value="Remove new Fields added" class="positive" disabled>
<img src="add.png" />
Remove fields added
</button>
</div class="buttons">
<br>
<br>
<hr>
<input type="checkbox" onclick="removeFields(this);">Remove fields added

</form>
 
</body>
</html>

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 22

Accepted Solution

by:
kadaba earned 500 total points
ID: 33580082
a variation from the first one, this stores the values as is...
lot of improvisation could be done.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript - Extending forms</title>
<!-- FROM QUIRKSMODE -->
<script type="text/javascript">
<!--
var divAdded = new Array(); 
var divCount = 0;

function moreFields(nodeToClone, isReplace) 
{
	var newFields = document.getElementById(nodeToClone).cloneNode(true);
		
	if(isReplace)
	{
		cloneInfo(nodeToClone,'div_newcontent');
	}
	else
	{
		cloneInfo(nodeToClone,'div_'+divCount);
		divAdded[divCount] = 'div_'+divCount;
		divCount++;	
	}	
}

var removedDiv = new Array();
var removedDivCount = 0;
function removeFields(chkObj){
	if(chkObj.checked)
	{
		for(var i=0;i<divAdded.length;i++)
		{
			if(document.getElementById(divAdded[i]))
			{
				removedDiv[removedDivCount] = new Array(2);
				removedDiv[removedDivCount][0] = divAdded[i];
				removedDiv[removedDivCount][1] = document.getElementById(divAdded[i]);
				removedDivCount++;
				document.forms[0].removeChild(document.getElementById(divAdded[i]));
			}
		}
		divCount = 0;
		divAdded = new Array();
		moreFields('newreadroot',true);
	}
	else
	{
		document.forms[0].removeChild(document.getElementById('div_newcontent'));
		for(var i=0;i< removedDiv.length;i++)
		{
			divAdded[divCount] = removedDiv[i][0];
			var insertHere = document.getElementById('writeroot');
			insertHere.parentNode.insertBefore(removedDiv[i][1],insertHere);
			divCount++;
		}
		removedDiv = new Array();
		removedDivCount = 0;
	}	
}

function cloneInfo(nodeToClone,id) 
{
	var newFields = document.getElementById(nodeToClone).cloneNode(true);
	newFields.id = id;
	newFields.style.display = 'block';
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

function removeFromFieldsArray(val)
{	var index;
	var temp = new Array();
	for(var i=0;i<divAdded.length;i++)
	{
		if(divAdded[i] != val)
		{
			temp[temp.length] = divAdded[i];
		}
	}
	divAdded = temp;
}

window.onload = function(){
	moreFields('readroot',false);
};

 
// -->
</script>
</head>
 
<body>
 
<h3>Example</h3>
 
<form id="request" action="" method="post">
<div id="readroot" style="display:none">
<input type="button" value="Remove transcript destination" onclick="this.parentNode.parentNode.removeChild(this.parentNode);removeFromFieldsArray(this.parentNode.id)" src="delete.png" alt="Remove transcript destination"/>
<br />
 
<label for="HowMany">Number of transcripts to be sent to this address</label>:
<br />
<input name="HowMany[]" id="HowMany" class="required" title="Number of transcripts" maxlength="2" size="2"/>
<br />
 
<label for="Name">Name</label>
<br />
<input name="Name[]" id="Name" class="required" title="Enter the name" maxlength="25"/>
<br />
 
<label for="DCity">City</label>
<br />
<input name="DCity[]" id="DCity" class="required" title="Enter your City" maxlength=""/>
<br />
 
<label for="Timing">When Should the transcript be sent?</label>
<br />
 
<select id="Timing" name="Timing[]"  class="validate-selection">
<option value="X">Select</option>
<option value="1">Now</option>
<option value="2">When semester grades are posted</option>
<option value="3">When degree statement is posted</option>
</select>
</div id="readroot">

<div id="newreadroot" style="display:none;border:1px solid black;width:650px">
This is where the new content will be added.<br>
Sample Text: <input type="text" id="newText"><br>
Sample Radios:<input type="radio" id="rad1" name="radGrp"> 1 <input type="radio" id="rad2" name="radGrp">2<br>
Sample select:
<select id="ddsel">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">4</option>
</select>
<br>
Sample check box: <input type="checkbox" id="chkbx"><br>
</div>

 
<span id="writeroot"></span id="writeroot">
<br> 
<div class="buttons">
<button type="button" id="btnMore" onClick="moreFields('readroot',false);" value="Add another transcript destination" class="positive">
<img src="add.png" />
Add another transcript destination
</button>
 
<button type="submit" class="positive">
<img src="bullet_go.png" />
Submit Completed Form
</button>

<button type="button" id="removeAll" onclick="removeFields();" value="Remove new Fields added" class="positive" disabled>
<img src="add.png" />
Remove fields added
</button>
</div class="buttons">
<br>
<br>
<hr>
<input type="checkbox" onclick="removeFields(this);">Remove fields added

</form>
 
</body>
</html>

Open in new window

0
 

Author Comment

by:aberns
ID: 33580096
kadaba,

I think that's it!

Let me put it through some paces later, and I'll get back to you with feedback points in a few hours.

Thanks again!!!!
0
 

Author Closing Comment

by:aberns
ID: 33589436
Thank you so much!!!!! I admire your skills!

AB
0
 
LVL 22

Expert Comment

by:kadaba
ID: 33589584
Thank you.

Feel free to ask anything if you have any concerns.
Have a nice day.

-$kadaba
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now