View Single Post
Old 09-13-2012, 11:38 PM   PM User | #1
RGVBaptist
New to the CF scene

 
Join Date: Sep 2012
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
RGVBaptist is an unknown quantity at this point
Problem with setting onclick function using createElement

I'm not very good at Javascript, but I can usually get done what I need to get done. Today, however, I've beat my head against the wall for hours and need some help.

I've got two simple functions. One adds a dynamic textbox and button to an existing form, the other removes the box/button. Any number of box/button combinations can be added.

The add code works fine. The remove code works fine IF I STATICALLY ADD THE BOX/BUTTON AND REFERENCE THE REMOVE CODE. However, if I dynamically add the box/button, the button never calls the remove code. I've tried a bunch of different ways, but it just sits there. Here's the code:

Code:
<script type="text/javascript">
function RemoveTask(intTaskNumber)
{
	strFieldName = "txtTask" + intTaskNumber;
	strFieldName2 = "btnTask" + intTaskNumber;
	
	var objHandler = document.getElementById("lstValues");
	objHandler.removeChild(document.getElementById(strFieldName));
	objHandler.removeChild(document.getElementById(strFieldName2));
	
	alert("Delete Code Invoked");
}
</script>

<script type="text/javascript">
function formvalidation(frmValues)
{

	intCount = document.frmTestData.txtTaskCount.value;
	intCount = parseInt(intCount) + parseInt(1);
	document.frmTestData.txtTaskCount.value = intCount
	
	strFieldName = "txtTask" + intCount;
	strFieldName2 = "btnTask" + intCount;
	alert('Name: ['+strFieldName2+']');
	strSubName = "RemoveTask(" + intCount + ");"

	var element = document.createElement("input");
	element.setAttribute("type", "Textbox");
	element.setAttribute("value", document.frmValues.txtNewValue.value);
	element.setAttribute("name", strFieldName);

	var foo = document.getElementById("lstValues");
 
    //Append the element in page (in span).
	foo.appendChild(element);
    
	var button = document.createElement("button");
	button.value = "Remove Task";
	button.name = strFieldName2;
	button.onclick = function(){RemoveTask(intCount);};

	var foo = document.getElementById("lstValues");
 
    //Append the element in page (in span).
	foo.appendChild(button);
	
	document.frmValues.txtNewValue.value = "";

	return false;
}
</script>
Any ideas?
RGVBaptist is offline   Reply With Quote