0

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?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • 4
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Turnip Aug 07 '16 at 18:01
  • "replaced at runtime" by what? Can that same code also add the code for the handler? Can you create a handler on `document` and filter by `id` values? It seems like there's more to this than we're seeing. – David Aug 07 '16 at 18:03
  • Why not using class? – Ibrahim Khan Aug 07 '16 at 18:03
  • you can make a common function which takes in one parameter as the `ID` of that respective element and performs different operation based on the ID, then bind `onclick='function(this.id)'` to the input. Dynamically they can be injected by the `setAttribute` method to be called upon the element. – Utkarsh Vishnoi Aug 07 '16 at 18:17

2 Answers2

1

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));
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74
1

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);
Rounin
  • 27,134
  • 9
  • 83
  • 108