Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript

Recently asked on Yahoo! Answers

Need a script that allows you to select a combination of pic and display a third pic based on pic. selection?

I’m looking for a html/java script that I can add to a website that will allow a user to select two different pictures and dependant on their selection, display a third picture. Any ideas?

It’s taken a while to find a question that was both interesting to me and something I could knock out inside of an hour or so, but I finally came across this one. This is a fairly straightforward use of JavaScript to manipulate the HTML DOM, and it allows me to expand upon previous DOM issues I’ve covered.

We’ll use checkboxes to select combinations of two out of four images, and then display a fifth image based on those choices.

The HTML Form

As always, we begin with a standard HTML form. This one will use checkboxes to select up to two images, and again, I’ll cheat on layout by using a table to line things up.

We’ll also create a DIV, which we’ll use to display the new image; and finally, we’ll add an onclick event to each of the checkboxes, named displayNewImage(). Note that the checkboxes don’t have ID attributes, and share the same name attribute. More on that shortly.

<form id="form1" name="form1">
<p>Select <strong>only two</strong> images below:</p>
  <table class="phototable">
    <tr>
      <td><img src="images/01.jpg" alt="01" width="179" height="250" /></td>
      <td><img src="images/02.jpg" alt="02" width="250" height="156" /></td>
      <td><img src="images/03.jpg" alt="03" width="250" height="177" /></td>
      <td><img src="images/04.jpg" alt="05" width="194" height="250" /></td>
    </tr>
    <tr>
      	<td>
	  		<label><input type="checkbox" name="myimages" value="01" id="myimages" onclick="displayNewImage()" />&nbsp;Select this image</label>
		</td>
		<td>
			<label><input type="checkbox" name="myimages" value="02" id="myimages" onclick="displayNewImage()" />&nbsp;Select this image</label>
		</td>
		<td>
			<label><input type="checkbox" name="myimages" value="03" id="myimages" onclick="displayNewImage()" />&nbsp;Select this image</label>
		</td>
		<td>
			<label><input type="checkbox" name="myimages" value="04" id="myimages" onclick="displayNewImage()" />&nbsp;Select this image</label>
		</td>
    </tr>
  </table>
</form>
  <br />
  <div id="newimage"></div>

The countCheckedBoxes() Function

Because we want to limit the user to only two image choices, we need to be able to count how many checkboxes are currently checked, and prevent more than two being chosen.

As a result, I’ve built a function that is going to handle when users check too many boxes; and, as a bonus, we’ll have that function help the next function, which will actually display the image.

First step: Declare the function and some variables. Also, we’ll use getElementsByName to get all the checkboxes and put them into a JavaScript array. Remember, whenever HTML pages have checkboxes with the same name, it handles the checkboxlist as an array; so, too, will JavaScript handle checkboxlists as an array.

We also need a global variable: checkedIndexes. This array is going to hold the last good set of selected checkbox indexes for us, so we can revert back to those boxes being checked, in case someone selects too many checkboxes. More on that shortly.

var checkedIndexes = new Array();

function countCheckedBoxes() {
	var counter = 0;
	var x;
	var theboxes = document.getElementsByName('myimages');

Now, we’ll loop through the checkboxlist, seeing which elements are checked. For each checked item, we will increment the counter by 1.

If there are more than two checked items, we will:

  • alert the user to only choose two items;
  • clear all the selected items from the checkbox list;
  • restore all the previously checked items back to the checkboxlist; and
  • return the current counter total.
	for(i = 0; i < theboxes.length; i++) {
		if(theboxes[i].checked) {
			counter++;
			if(counter > 2) {
				alert('Please only check two boxes!');

				for(x = 0; x < theboxes.length; x++) {
					theboxes[x].checked = false;
				}
				for(x = 0; x <= 1; x++) {
					theboxes[checkedIndexes[x]].checked = true;
				}

				return counter;
			}
		}
	}

If we don’t have more than 2 checked items, we either have 0, 1 or 2 checked items. Whichever the case, we have a good set of selected checkboxes, so we want to store the indexes of the selected checkboxes into the checkedIndexes array we previously declared.

Finally, we’ll return the current value of the counter.

	x = 0;
	for(i = 0; i < theboxes.length; i++) {
		if(theboxes[i].checked) {
			checkedIndexes[x] = i;
			x++;
		}
	}

	return counter;

The displayNewImage() Function

This function will actually go about placing the new image into the DIV we declared back in the form. We begin by declaring the function, declaring string variables that will hold the info we need to display the new image, setting the image DIV into a JavaScript object, and getting the return value from countCheckedBoxes():

function displayNewImage() {
	var imagediv = document.getElementById('newimage');
	var result = countCheckedBoxes();
	var imageSrc = '';
	var imgUrl = '';

Next, we ask if there are two checked boxes. If so, we know we need to display the new image, so we get the indexes of the checked boxes from our global checkedIndexes array and set them to new variables.

Next, we use nested switch() statements to cover every possible combination of check box selections. Since the first index (i) will always be the lower than the second index (x), we need only cover higher values in the second index (x).

Whatever our combination, we set the imageSrc string to be the name of the appropriate image:

	if(result == 2) {
		var i = checkedIndexes[0];
		var x = checkedIndexes[1];

		switch(i) {
			case 0:
				switch(x) {
					case 1:
						imageSrc = '05.jpg';
						break;
					case 2:
						imageSrc = '06.jpg';
						break;
					case 3:
						imageSrc = '07.jpg';
						break;
				}
				break;
			case 1:
				switch(x) {
					case 2:
						imageSrc = '08.jpg';
						break;
					case 3:
						imageSrc = '09.jpg';
						break;
				}
				break;
			default:
				imageSrc = '10.jpg';
		}

At long last, we can display the new image. We set the URL for the image to be the full HTML tag for the image, concatenating on the value of imageSrc where appropriate.

Finally, we set the innerHTML property for our DIV to be the IMG tag we just created.

		imgUrl = '<h3>Your new image:</h3>\n';
		imgUrl += '<img src="images/' + imageSrc + '" alt="' + imageSrc + '" />';
		imagediv.innerHTML = imgUrl;
	}

Lastly, we clear the displayed image from the screen — by setting the DIV’s innerHTML to be an empty string — if there are less than 2 checked boxes.

	else if(result < 2) {
		imagediv.innerHTML = '';
	}
}

That’s all there is to it: Any two — and only two — choices from our four starting photos will yield a unique, new image.

You can see a working demo of this here:

http://www.dougv.com/demo/js_select_images/

You can download the source code for this here:

Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript Demo Code

As always, I distribute code under the most recent version of the Creative Commons Attribution / Share-Alike License.


3 Responses to “Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript

Leave a Reply