3

I am creating some buttons dynamically and assigning them IDs.

When ever someone clicks that button I want to collect the ID and from there perform some task.

Here's my work in progress

$(document).ready(function() {
    $('input:button').addClass("btnClass");
    fillData();
    $('#btnGet').click(function() {
        fillData();
    });
    function fillData() {
        $.ajax({
            type: "Post",
            url: "../Linq/myService.asmx/getStudent",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //var nMsg = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
                var t = "<table width='80%' id='resTab'> <tr>" +
                      "<td colspan='5' style='text-align:center'><font size='3'><strong>Your Search Result......</strong></font></td></tr> <tr><td style='text-align:left' colspan='5'><hr></td></tr> "
                      + " <tr><td style='text-align:center'>Student ID</td><td style='text-align:center'>Student Name</td><td style='text-align:center'>Student Course</td><td style='text-align:center'>Student USN</td></tr>"
                      + " <tr><td style='text-align:left' colspan='5'><hr><br></td></tr> ";
                $.each(msg.d, function(index, item) {
                    t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete' onClick='onButtonClick()'/></td></tr>";
                    t = t + " <tr><td style='text-align:left' colspan='5'><hr></td></tr> ";
                });
                t = t + " </table> ";
                $("#stdData").html(t);
            },
            error: function(msg) { }
        });
    }


function onButtonClick() {
    var btnId = $(this).val();
    alert(btnId);
}
Marko
  • 71,361
  • 28
  • 124
  • 158
Umakanta.Swain
  • 1,107
  • 2
  • 13
  • 24

5 Answers5

14

Just add a class name of new-button to the buttons you're creating and add a click handler afterwards.

So replace this code

<input type='button' ID='btn"

with this

<input type='button' class="new-button" ID='btn"

You can remove the onButtonClick() from the onclick event and replace

function onButtonClick() {
    var btnId = $(this).val();
    alert(btnId);
}

with

$(".new-button").live("click", function() {
    var buttonId = $(this).attr("id");
    alert(buttonId);
});
Marko
  • 71,361
  • 28
  • 124
  • 158
  • You're welcome - check out the FAQ on how to use the website and if I solved your problem - tick the green tick that's just to the left of this answer <<<<----- – Marko Sep 16 '10 at 07:06
  • since jquery 1.9 instead of live you should use "on" – sd1sd1 Nov 11 '13 at 19:56
1

I am not sure I understand exactly your problem, but you can try writing

var btnId = $(this).attr('id');

instead of

var btnId = $(this).val();

this will give you the id attribute of the button clicked and not the value of the form element.

I hope this will help you

Jerome Wagner

Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77
1

If you are dynamically adding buttons, think about using ".live()". Whenever the specified event happens, it follows the html elements up the tree until it is handled. This is more efficient if you have a lot of elements also because the event isn't assigned to the element itself. You need to assign a class or something to the buttons to identify them, let's say 'dynamicButton', so change this:

<input type='button' ID='btn" + item.studId + 
"' value='Delete' onClick='onButtonClick()'/>

to this:

<input type='button' ID='btn" + item.studId + 
"' value='Delete' class="dynamicButton"/>

And you can listen to events with this code:

$('input.dynamicButton').live('click', function (event) {
        alert($(this).attr('id'));
    });

This one handler will be called anytime a button with the class 'dynamicButton' is clicked no matter how it is added to the page.

Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
0

I did this using delegate(). In my case, a PHP script generates the content of a page from a MySQL database. To each element, a button is added (clicking these buttons can remove the respective element from the database). The removal is handled by another PHP script which these buttons activate, so a click event is attached to each button like this:

$('.items').delegate('[type="button"]', 'click', remove_item);

where the buttons are part of the items class and remove_item is the callback for the removal.

TMOTTM
  • 3,286
  • 6
  • 32
  • 63
0

When ever someone ll click that button I want to collect the ID and from there I ll do some task upon that.............

Try removing onclick attribute from this line:

t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete' onClick='onButtonClick()'/></td></tr>";

Making it:

t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete'/></td></tr>";

And now you can use jQuery's live method (since your button is generated dynamically) to do the trick when this button is clicked like this:

$(function(){
  $('#btn').live('click', function(){
     var btnId = $(this).attr('id');
     alert(btnId);
  });
});

Note:

To get id attribute, you can use attr method like shown above eg: $(this).attr('id') not val (which is used to get the value of an input element) like your in your code.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • His buttons are named #btn1, #btn2 etc.. Targeting #btn will fail, and even if all the buttons were called #btn, it would be invalid mark up and IE would only select 1 element. See my class solution above. – Marko Sep 16 '10 at 07:05