Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

How to add click listener to dynamically added button?

I'm adding a button dynamically by doing:

<input id="{Id}" type="submit" value="View">

{Id} is replaced at runtime with the record id.

I would like to have a function like:

function viewRecord(button) {
    //Do something here...
}

How can I add a click listener to the button that corresponds to the correct button being clicked?

I've started learning jquery today and would like an answer that shows how it's implemented.

EDIT

Based on the answer below, I'm trying the following:

<td><input class="viewRecord" type="submit" value="View"></td>

$(".viewRecord").click(function () {
    var $table = $('#table'),
    var $tableBody = $table.find('tbody'),
    var $text = $tableBody.closest('tr').attr('id');

    alert($text);
});

However, no alert is being displayed.

Am I missing something?

Upvotes: 0

Views: 187

Answers (2)

Rounin
Rounin

Reputation: 29453

Two steps:

1) Find the input with:

var dynamicButton = document.getElementById('{Id}');

2) Add the click Event Listener with:

dynamicButton.addEventListener('click',function(){viewRecord(dynamicButton.id);},false);

Upvotes: 1

Mohammad Akbari
Mohammad Akbari

Reputation: 4766

use following code:

<div id="container">
    <input id="{Id}" type="submit" value="View" class="dynamic-btn" />
</div>

(function($) {
    var btnClick = function(){
        var id = $(this).attr('id');
        alert(id);
        /*Do smth that you needed*/
    };

    $(function() {
        $("#container").on("click", ".dynamic-btn", btnClick)
    });

}(jQuery));

Upvotes: 1

Related Questions