I simply create the text-boxes with the name/id/event-handler built in at the time of generation:
Something like this, in a most generic way:
<?php
function addElement($i) {
$elemID = "elem$i";
return "<element name='$elemID' id='$elemID'
onEvent='eventHandler(\"$elemID\")'></element>";
}
?>
And call this type of function to generate your element, with various values for $i (such as sequential integers).
Remember, the function is a template - you need to modify it to your needs. an <input> element, for example, would not have a closing tag.
Note, also, that I didn't break the php up into a lot of small script intermixed with the HTML. Often that makes it just too difficult to read and thus buggy.