View Single Post
Old 12-09-2007, 03:04 AM   #5 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

I wrote a slightly fuller example, more to keep me occupied than anything else, which might be of use. Instead of hard-coding the HTML to be repeated, I told prototype to use what's already in the HTML -- that might be super useful, or superfluous, for you.

The essential function makes use of some of Prototypes great features:
JavaScript Code:
function addChoice()
{
    var choice = $('choice');
   
    // Prevent more than x copies
    if (choice.select('input[name="poll_choice[]"]').size() >= 10)
    {
        return;
    }
   
    // Make a copy of the pre-existing HTML that we want to repeat
    var clone = choice.select('span').first().cloneNode(true);
   
    // Clear any text boxes
    clone.select('input[type=text]').invoke('clear');
   
    // Insert the copy into the page
    choice.insert({'bottom': clone});
}

A full test page
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Cloning elements with Prototype</title>
	<script type="text/javascript" src="prototype.js"></script>
	<script type="text/javascript">
		function addChoice()
		{
			var choice = $('choice');
			
			// Prevent more than x copies
			if (choice.select('input[name="poll_choice[]"]').size() >= 10)
			{
				return;
			}
			
			// Make a copy of the pre-existing HTML that we want to repeat
			var clone = choice.select('span').first().cloneNode(true);
			
			// Clear any text boxes
			clone.select('input[type=text]').invoke('clear');
			
			// Insert the copy into the page
			choice.insert({'bottom': clone});
		}
	</script>
</head>
<body>
	<p id="choice">
		<span style="display: block; padding-bottom: 5px">
			<label for="poll_choice">Option</label>
			<input name="poll_choice[]" type="text" size="25" />
		</span>
	</p>
	<p>
		<button onclick="addChoice()">Add Choice</button>
	</p>
</body>
</html>

If you really want to keep the HTML hard-coded then a viable option would be:
JavaScript Code:
function addChoice()
{
    var choice = $('choice');
   
    if (choice.select('input[name="poll_choice[]"]').size() >= 10)
    {
        return;
    }
   
    choice.insert('<span style="display: block; padding-bottom: 5px"><label for="poll_choice">Option</label><input name="poll_choice[]" type="text" size="25" /></span>');
}
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
CMellor (12-09-2007)