How to access dynamically created objects in javascript?

advertisements

I have created a dynamic table and I want to access one of the created objects in a javascript. For example: How do I adress a dynamicly created button?

<script type="text/javascript">
function myJavaScriptFunction()
{
 //How do I know here which button triggered the function?
}
</script>

<table>
<% for (var i=0; i<10; i++) { %>
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction()"/>
   </td>
 </tr>
<% } %>
</table>

Thank you in advance /John


Map out the parameter to be the object:

function myJavaScriptFunction(object)
{
 //How do I know here which button triggered the function?
    var id = object.id;
}

In your HTML, you'll need to do:

onclick="myJavaScriptFunction(this)"

This is the point where you call the function, and you pass in the this keyword as an argument.

The keyword this refers to whichever HTML element did the calling, which is whatever button you clicked. The object has the attribute id which you have defined in the function as object.id. The value of attribute id is basically the "id" field of the input tag.

Putting it all together, you get:

<script type="text/javascript">
function myJavaScriptFunction(object) // You're defining the function as having a parameter that it accepts. In this case, it accepts an object.
{
   alert(object.id); // Alert the object's id.
   // Do what you want with object.id
}
</script>

<table>
<% for (var i=0; i<10; i++) { %>
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction(this)"/>
   </td>
 </tr>
<% } %>
</table>