I have a question regarding the html class attribute interactive with the javascript call back.
Suppose I have a table and each row has a button like this:
<table border="0">
<?php foreach ($itemlist as $item => $value): ?>
<tr>
<td><?php echo $item;?></td>
<td><button class="create-user">Test</button></td>
</tr>
<?php endforeach; ?>
</table>
Notice that the button has a class attribute as “create-user”. Now I want to add the same callback for each button with this:
var btn = document.getElementsByClassName("create-user");
btn.click(function() {
$("#dialog-form").dialog("open");
});
I expected the dialog-form will open up but there is no response. This is my first time to deal with the class attribute along with javascript.
Can anyone shed some light for me?
Thanks!
getElementsByClassNamereturns an array-like collection (technically anodeList). To add an event handler to your elements, you’ll have to loop through them:However, since you’re using jQuery, you should use jQuery to select your elements, which won’t require an explicit loop:
P.S. For increased performance, remember to cache your selectors: