Posts tagged ‘html’

Using Javascript to hide single/multiple div tags with the same name Part 2

Recently I was asked by a comment from my previous post Using Javascript to hide single/multiple div tags with the same name on how to get multiple buttons to control multiple div tags. For example, 2 div classes need to be hidden or shown with 2 different buttons controlling them. Turns out this is fairly simple. Basically you can use some previous code and alter some variable names in the javascript, but to make things simple here is the code.

function getElementsByClass(searchClass, domNode, tagName) {
     if (domNode == null) domNode = document;
     if (tagName == null) tagName = '*';
     var el = new Array();
     var tags = domNode.getElementsByTagName(tagName);
     var tcl = " "+searchClass+" ";
     for(i=0,j=0; i<tags.length; i++) {
          var test = " " + tags[i].className + " ";
          if (test.indexOf(tcl) != -1)
               el[j++] = tags[i];
          }
     return el;
}
 
var hidden = false;
function toggle_hideme1() {
     hidden = !hidden;
     var newDisplay;
     if(hidden) {
          newDisplay = 'block';
     }
     else
     {
          newDisplay = 'none';
     }
     var showfirst = getElementsByClass("div_class_name", null, "div");
     for(var i = 0; i < showfirst.length; i++) {
          showfirst[i].style.display = newDisplay;
     }
}
 
var hiddenb = false;
function toggle_hideme2() {
     hiddenb = !hiddenb;
     var newDisplay;
     if(hiddenb)
     {
          newDisplay = 'block';
     }
     else
     {
          newDisplay = 'none';
     }
     var showsecond = getElementsByClass("div_class_name", null, "div");
     for(var k = 0; k < showsecond.length; k++) {
          showsecond[k].style.display = newDisplay;
     }
}

For the variables ‘showfirst’ and ‘showsecond’ you can call them what ever you want, just make sure they stay the same in only one function, not two. Be sure to change ‘div_class_name’ to a custom name for each field.

Also, these are setup to be hidden first, you can change that by swapping the ‘newDisplay = ‘ lines.

For the HTML code we are going to use check boxes. We need two boxes each with names that call the function.

<input type="checkbox" name="showone" id="showone" value="showone" onClick="toggle_hideme1('showone');"><br />
<input type="checkbox" name="showtwo" id="showtwo" value="showtwo" onClick="toggle_hideme2('showtwo');"><br />

If you want the boxes checked to start first swap the ‘newDisplay =’ lines, and use this.

<input type="checkbox" name="showone" id="showone" value="showone" onClick="toggle_hideme1('showone');" CHECKED><br />

As in my previous post you need to put what ever will be shown or hidden in a div class tag.

<div class="div_class_name" style="display: none;">

The style hides everything in the class until the box is checked.

That will start the boxed checked, when you un-check it the data in all div classes with that name will hide (remember the ‘div_class_name’? that’s what we are working with).

I wrote this up in just a couple minutes, so I truly help it makes scene. You can check out an example of how it works here.

Dynamically add form fields using javascript and DOM with dynamic post method

Lets say you need to add some extra text fields but you don’t want to write a bunch of code. I not only have how to quickly and easily add the input fields, but also how to take the data and put in into a MySQL DB!

I start with creating the DB. Lets call the table ‘phone’. We need 3 rows. ‘idx’ int(10) with Auto Increment and primary key. ‘name’ varchar(30), and ‘numb’ varchar(20). You can setup the db how ever you choose. I create the idx so that I have a key field.

Now we need some javascript.

var counter = 0;
Start a counter. Yes, at 0
function add_phone() {
    counter++;
// I find it easier to start the incrementing of the counter here.
    var newFields = document.getElementById('add_phone').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
                newField[i].name = theName + counter;
// This will change the 'name' field by adding an auto incrementing number at the end. This is important.
        }
        var insertHere = document.getElementById('add_phone');
// Inside the getElementById brackets is the name of the div class you will use.
        insertHere.parentNode.insertBefore(newFields,insertHere);
}

Now I like to put that in a seperate .js file, but you can add it to your HTML HEAD tag.

Next we need to build the form.

<form name="add_a_phone" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div id="phone">
    <input type="text" name="phone_0" value="" />
    <input type="text" name="phone_num_0" value="" /><br>
</div>
<div id="add_phone" style="display: none;">
    <input type="text" name="phone_" value="" />
    <input type="text" name="phone_num_" value="" /><br>
</div>
<input type="button" id="add_phone()" onclick="add_phone()" value="Give me more fields!" /><br>
<input type="submit" name="submit" value="submit" />
</fieldset>
</form>

Notice how in the input button field that the ‘id’ and ‘onclick’ are the same. That’s important, and yes you do need the brackets for some reason.
Also note that the form name can NOT be the same as any div id!!! I keep making that mistake.
You will need some way of checking how many fields were added when you get to your ‘if(isset($_POST[‘submit’))’ statement. This gets a little messy.
Because I like my forms to go back to this page and check if submit was clicked we need to put some php code at the very top.

<?php
    if(isset($_POST['submit']))
    {
        echo "You clicked submit!<br>";
        echo "Here is your data<br>";
        echo "<br>";
        if ($_POST['phone_num_0'])
        {
                $continue = FALSE;
                $i = 0;
                while ($continue == FALSE)
                {
                    if (isset($_POST['phone_'.$i]))
                    {
                    echo $_POST['phone_'.$i] . " = " . $_POST['phone_num_'.$i] . "<br>";
                    $phone = $_POST['phone_'.$i];
                    $phone_num = $_POST['phone_num_'.$i];
                    $query = "INSERT INTO phone (idx, name, numb) VALUES ('NULL', '$phone', '$phone_num')";
                    $result = mysql_query($query);
                }
                else
                {
                    $continue = TRUE;
                }
                $i++;
            }
        }
    }
?>

Obviously I left out some information. Like connecting to your DB. I’m assuming you already know how to do that.

I first wrote this on my main page. This post is almost a copy/paste from the main page. I like adding it to the blog since it gets better indexing from search engines and hopefully the information will be useful to you. On the main page there is also a working example so you can see how it all ties in. Check it out Here

Questions?

Using Javascript to hide single/multiple div tags with the same name

Update (March 25th, 2009):
I have created a page on the main site so that you can see how the code works, it may be easier to read than this. Check it out here

After scouring the net for information I finally got my answer from JimmySeal at TechGuy.org. Turns out the process is very simple.

In my first example I want to hide just one div tag when a check box is clicked. The process is a simple one, all we need to do is create a div with an id argument. Like div id=”hideme”. I prefer to use external js files to hold my javascript functions. Lets call it junctions.js. In this file lets put this bit of code.

function toggle_visibility(hideme)
{
	var e = document.getElementById(hideme);
	if(e.style.display == 'block')
		e.style.display = 'none';
	else
		e.style.display = 'block';
}

This will hide the div tag with id hideme
So in my html file I have something like this. (My example is in an input form)

<b>Show the field</b><input type="checkbox" name="a_name" value="a_name" onClick="toggle_visibility('hideme');">
<div id="hideme" style="display:block;">
	<b>was hidden</b><textarea name="some_name" cols="40" rows="5"></textarea><br />
</div>

Notice that the div id and the onClick functions are the same name, hideme. That’s it! How when the box is checked it will hide that one div tag.

What if you want to hide multiple div tags. Unfortunately the above script will not work simply because you can’t have more than one div id per page. You must use div class.

Open up your functions.js file and put this in.

var hidden = false;
function getElementsByClass(searchClass, domNode, tagName) {
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) {
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1)
		el[j++] = tags[i];
	}
	return el;
}
 
function toggle_hideme()
{
	hidden = !hidden;
	var newDisplay;
	if(hidden)
	{
		newDisplay = 'none';
	}
	else
	{
		newDisplay = 'block';
	}
	var hellos = getElementsByClass("div_class_name", null, "div");
	for(var i = 0; i < hellos.length; i++)
	{
		hellos[i].style.display = newDisplay;
	}
}

Now for the form code example

<input type="checkbox" name="a_name" value="a_name" onClick="toggle_hideme('div_class_name');">
<div class="div_class_name">
	Blah Blah Blah
</div>
<div class="something_else">
	What ever is here will not disappear!
</div>
<div class="div_class_name">
	more blah blah blah
</div>

The only thing you need to pay attention to here is div_class_name just change it to what ever you want to call your div tag.

EDIT NOTE:
I just want to say that I’ve been getting a lot of hits here, but no one leaves me any comments. How do I know if this is helpful? Please leave a comment. I won’t sell your e-mails or anything. If you so desire enter in a fake e-mail, I don’t care. I just want to know. Thank you.

UPDATE!
http://blog.tangorangers.com/2009/08/using-javascript-to-hide-singlemultiple-div-tags-with-the-same-name-part-2/