1

I have a few different modals on my page that need data passed into them. I solved that problem with this other question, which has me using jQuery now and was really helpful. This is what I have now:

$(document).on("click", ".edit", function () {
    $(".modal-body #value").val($('.edit').data('id'));
});

My problem is that since my page has dynamically created buttons (from a foreach based on the model), no matter which button I click, this gets the value from the first button. How do I instead get the value from the button that was clicked.

I thought about giving them all separate ids, but I don't want to make a function for each id. I read that there is a data property to this .on method, but I can't find a good example of how to use it and if it would work in my case.

If anyone has any suggestions I would be very grateful. Thank you!

Community
  • 1
  • 1
Bobo
  • 976
  • 2
  • 10
  • 25

3 Answers3

5
$(document).on("click", ".edit", function () {
    // Use $(this) to reference the clicked button
    $(".modal-body #value").val($(this).data('id')); 
});
sjobe
  • 2,817
  • 3
  • 24
  • 32
  • 1
    oh wow I can't believe it was that easy. I always forget about the magical `this` word. I'll accept this soon as I can in 10 minutes! – Bobo Jun 09 '14 at 16:23
1

You can reference the button being clicked by using the this keyword. Try the following:

$(document).on("click", ".edit", function () {
    $(".modal-body #value").val($(this).data('id'));
});
xcopy
  • 2,248
  • 18
  • 24
0

Use Bootstrap's events:

$('#your-modal').on('show.bs.modal', function (e) {
    var btn = $(e.relatedTarget);
    var id = btn.data('id');
    $("#value").val(id);
});

See the "Events" section of http://getbootstrap.com/javascript/#modals :

[The show.bs.modal event] fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

cvrebert
  • 9,075
  • 2
  • 38
  • 49