614

I've got a couple of hyperlinks that each have an ID attached. When I click on this link, I want to open a modal ( http://twitter.github.com/bootstrap/javascript.html#modals ), and pass this ID to the modal. I searched on google, but I couldn't find anything that could help me.

This is the code:

<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>

Which should open:

<div class="modal hide" id="addBookDialog">
    <div class="modal-body">
        <input type="hidden" name="bookId" id="bookId" value=""/>
    </div>
</div>

With this piece of code:

$(document).ready(function () {
    $(".open-AddBookDialog").click(function () {
        $('#bookId').val($(this).data('id'));
        $('#addBookDialog').modal('show');
    });
});

However, when I click the hyperlink, nothing happens. When I give the hyperlink <a href="#addBookDialog" ...>, the modal opens just fine, but it does't contain any data.

I followed this example: How to pass values arguments to modal.show() function in Bootstrap

(and I also tried this: How to set the input value in a modal dialogue?)

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Leon Cullens
  • 12,276
  • 10
  • 51
  • 85

16 Answers16

605

I think you can make this work using jQuery's .on event handler.

Here's a fiddle you can test; just make sure to expand the HTML frame in the fiddle as much as possible so you can view the modal.

http://jsfiddle.net/8c05pn1f/

HTML

<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<p>&nbsp;</p>


<p>Link 2</p>
<a data-toggle="modal" data-id="ISBN-001122" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
    
<div class="modal hide" id="addBookDialog">
 <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
  </div>
    <div class="modal-body">
        <p>some content</p>
        <input type="text" name="bookId" id="bookId" value=""/>
    </div>
</div>

JAVASCRIPT

$(document).on("click", ".open-AddBookDialog", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val( myBookId );
     // As pointed out in comments, 
     // it is unnecessary to have to manually call the modal.
     // $('#addBookDialog').modal('show');
});
mg1075
  • 17,985
  • 8
  • 59
  • 100
  • 5
    This works fine when I have only one hyperlink, but I have multiple hyperlinks, each with their own ID. I added a second hyperlink with another ID, but the modal always has the ID of the first hyperlink. – Leon Cullens May 17 '12 at 13:47
  • 1
    @LeonCullens - I've updated the fiddle and the code. Does it work the way you want now? – mg1075 May 17 '12 at 13:56
  • 2
    Good answer - but is the `modal('show')` required? Seems like the `data-toggle="modal"` on the links would take care of that. – technophobia Feb 07 '13 at 19:40
  • @technophobia - Correct! The `data-toggle="modal"` does make the `$(...).modal('show')` call superfluous. http://jsfiddle.net/55ZWe/1/ – mg1075 Feb 07 '13 at 20:45
  • 1
    Actually, it's not superfluous to call the modal within the event handler. If you leave it to the `data-toggle` the order the events fire is left to the browser and is not consistent. Much better to call the modal via JS. – David Barker Jul 15 '13 at 12:56
  • 9
    just the `$(this).data('id');` was priceless on it's own! I had no idea that you could get the data attribs with that. I'm loving bootstraps more each day! =P – Manatax Jul 29 '13 at 23:52
  • 27
    @Manatax - `$(this).data()` is part of jQuery. http://api.jquery.com/data/#data-html5 – mg1075 Jul 30 '13 at 03:19
  • 1
    The fiddle does not work, it does not open a modal. The code shows 2 steps: 1. prepare data for the modal after the btn click and 2. then open the modal with the prepared data? – Timo Jul 09 '22 at 11:00
  • 1
    @Timo - Thanks for pointing that out. The jsfiddle was giving a 404 on the bootstrap 2.0.2 js file. Have now made a fork of original fiddle and have it serving bootstrap from cdnjs to get rid of the 404; purposely not updating to latest versions of all the libraries, as I want to keep answer as close to original answer as possible. – mg1075 Jul 09 '22 at 20:40
432

Here is a cleaner way to do it if you are using Bootstrap 3.2.0.

Link HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

Modal JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});

http://jsfiddle.net/k7FC2/

LostInComputer
  • 15,188
  • 4
  • 41
  • 49
  • 1
    $(e.currentTarget).find('input[name="bookId"]').val(bookId); can you tell me what does this do? So if the modal is open meaning the value of the input name bookId is the value from which it was clicked right? – hale Feb 04 '16 at 03:28
  • 1
    @treblaluch `e.currentTarget` is the clicked element, which is taken from the click event `e`. This line finds an `input` with the name `bookId` and sets the value on it. – aalaap Sep 29 '17 at 13:20
  • This should be the accepted answer. I went through `e.relatedTarget.dataset.myDataId`. In fact, `data-*` are stored inside the dataset of the event relatedTarget. However, I don't know which one is the faster... – Devart Nov 18 '20 at 12:40
  • This one should be the accepted answer, I tried `$(this)` but didn't work, replacing it with `$(e.relatedTarget)` got the job done. Thanks! – Eihab Oct 13 '21 at 16:44
42

Here's how I implemented it working from @mg1075's code. I wanted a bit more generic code so as not to have to assign classes to the modal trigger links/buttons:

Tested in Twitter Bootstrap 3.0.3.

HTML

<a href="#" data-target="#my_modal" data-toggle="modal" data-id="my_id_value">Open Modal</a>

JAVASCRIPT

$(document).ready(function() {

  $('a[data-toggle=modal], button[data-toggle=modal]').click(function () {

    var data_id = '';

    if (typeof $(this).data('id') !== 'undefined') {

      data_id = $(this).data('id');
    }

    $('#my_element_id').val(data_id);
  })
});
J W
  • 2,801
  • 2
  • 18
  • 22
20

Bootstrap 4.3 - use code from below snippet - more here

$('#exampleModal').on('show.bs.modal', function (event) {
  let bookId = $(event.relatedTarget).data('bookid') 
  $(this).find('.modal-body input').val(bookId)
})
a.btn.btn-primary.open-AddBookDialog {color: white }
<!-- Initialize Bootstrap 4 -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<!-- BUTTON -->

<a 
  class="btn btn-primary open-AddBookDialog" 
  data-toggle="modal" 
  data-target="#exampleModal" 
  data-bookid="@book.Id" 
  title="Add this item"
>Open</a>

<!-- MODAL -->

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    
      <div class="modal-body">
        <input type="hidden" name="bookId" id="bookId" value=""/>
        <input type="text" class="form-control" id="recipient-name">    
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
17

If you are on bootstrap 3+, this can be shortened a bit further if using Jquery.

HTML

<a href="#" data-target="#my_modal" data-toggle="modal" class="identifyingClass" data-id="my_id_value">Open Modal</a>

<div class="modal fade" id="my_modal" tabindex="-1" role="dialog" aria-labelledby="my_modalLabel">
<div class="modal-dialog" role="dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal Title</h4>
        </div>
        <div class="modal-body">
            Modal Body
            <input type="hidden" name="hiddenValue" id="hiddenValue" value="" />
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            <button type="button" class="btn btn-primary">Yes</button>
        </div>
    </div>
</div>

JQUERY

<script type="text/javascript">
    $(function () {
        $(".identifyingClass").click(function () {
            var my_id_value = $(this).data('id');
            $(".modal-body #hiddenValue").val(my_id_value);
        })
    });
</script>
VTStampede
  • 313
  • 3
  • 7
11

Your code would have worked with correct modal html structure.

$(function(){
  $(".open-AddBookDialog").click(function(){
     $('#bookId').val($(this).data('id'));
    $("#addBookDialog").modal("show");
  });
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>


<a data-id="@book.Id" title="Add this item" class="open-AddBookDialog">Open Modal</a>

<div id="addBookDialog" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
       <input type="hidden" name="bookId" id="bookId" value=""/>
      </div>
    
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</html>
phil
  • 420
  • 4
  • 14
11

I'm with bootstrap 5 and cannot show() the modal with script myself due to constraints outside my control, so I'm depending on properties data-bs-toggle and data-bs-target of the button that pops up the modal.

Bootstrap exposes a few events though (https://getbootstrap.com/docs/5.0/components/modal/), to which we can hook code like so:

document.getElementById('idModal').addEventListener('show.bs.modal', (e) => {
    console.log(e.relatedTarget);
});

In relatedTarget, we'll find the specified data attributes in dataset, e.g. if we have an element that looks like this:

<button
    class="btn btn-secondary"
    data-id="fk_articles"
    data-bs-toggle="modal"
    data-bs-target="#documentationModal">
        Documentation
</button>

Then we can reach fk_articles through:

console.log( e.relatedTarget.dataset.id )
  • I had to adapt your version slightly to make it work with TypeScript/Angular, but it works and is the cleanest answer in my opinion! In my case, it regarded the ```e``` as a NORMAL Event, but it was a CustomEvent. This caused it to not find the ```relatedTarget``` property of ```e```. I had to write ```(e as any).relatedTarget``` to get access to its id! – MikhailRatner Mar 22 '22 at 17:05
7

This is so easy with jquery:

If below is your anchor link:

<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>

In the show event of your modal you can access to the anchor tag like below

//triggered when modal is shown
$('#modal_id').on('shown.bs.modal', function(event) {

    // The reference tag is your anchor tag here
    var reference_tag = $(event.relatedTarget); 
    var id = reference_tag.data('id')
    // ...
    // ...
})


Ehsan Ahmadi
  • 1,382
  • 15
  • 16
5

I find this approach useful:

Create click event:

$( button ).on('click', function(e) {
    let id = e.node.data.id;

    $('#myModal').modal('show', {id: id});
});

Create show.bs.modal event:

$('#myModal').on('show.bs.modal', function (e) {

     // access parsed information through relatedTarget
     console.log(e.relatedTarget.id);

});

Extra:

Make your logic inside show.bs.modal to check whether the properties are parsed, like for instance as this: id: ( e.relatedTarget.hasOwnProperty( 'id' ) ? e.relatedTarget.id : null )

Unicco
  • 2,466
  • 1
  • 26
  • 30
4

Bootstrap 4.0 gives an option to modify modal data using jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

Here is the script tag on the docs :

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

It works for the most part. Only call to modal was not working. Here is a modification on the script that works for me:

$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})
shaurya airi
  • 375
  • 4
  • 6
2

Try with this

$(function(){
 //when click a button
  $("#miButton").click(function(){
    $(".dynamic-field").remove();
    //pass the data in the modal body adding html elements
    $('#myModal .modal-body').html('<input type="hidden" name="name" value="your value" class="dynamic-field">') ;
    //open the modal
    $('#myModal').modal('show') 
  })
})
Dey
  • 842
  • 9
  • 21
  • But what if you close the Dialog, and open it for an other Element... you'll add 2 Hidden fields and it will be a mess once you send the form of the dialog – Pitzas Jun 03 '20 at 09:54
2

Found this works for me:

In the link:

<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>

In the modal:

<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
        <?php echo $row['id'];?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>
James Osguthorpe
  • 143
  • 3
  • 12
2

For updating an href value, for example, I would do something like:

<a href="#myModal" data-toggle="modal" data-url="http://example.com">Show modal</a>

$('#myModal').on('show.bs.modal', function (e) {
    var url = $(e.relatedTarget).data('url');
    $(e.currentTarget).find('.any-class').attr("href", "url");
})
1

This is how you can send the id_data to a modal :

<input
    href="#"
    data-some-id="uid0123456789"
    data-toggle="modal"
    data-target="#my_modal"
    value="SHOW MODAL"
    type="submit"
    class="btn modal-btn"/>

<div class="col-md-5">
  <div class="modal fade" id="my_modal">
   <div class="modal-body modal-content">
     <h2 name="hiddenValue" id="hiddenValue" />
   </div>
   <div class="modal-footer" />
</div>

And the javascript :

    $(function () {
     $(".modal-btn").click(function (){
       var data_var = $(this).data('some-id');
       $(".modal-body h2").text(data_var);
     })
    });
MaieonBrix
  • 1,584
  • 2
  • 14
  • 25
1

I think you don't need jQuery for that. You could use onclick event and pass bookId to javascript function where you query the element and set the value of the input.

<a data-toggle="modal" data-id="@book.Id" onclick="passBookId('@book.Id')" title="Add this item" class="open-AddBookDialog"></a>

and

<script>
    function passBookId(bookId) {
        let inputElement= document.document.querySelector("div.modal-dialog input[name='bookId'");
        if (inputElement) {
            inputElement.value = bookId;
        }
        return true;
    }
</script>
alex
  • 41
  • 2
-3

You can try simpleBootstrapDialog. Here you can pass title, message, callback options for cancel and submit etc...

To use this plugin include simpleBootstrapDialog.js file like below

<script type="text/javascript" src="/simpleDialog.js"></script>

Basic Usage

<script type="text/javascript>
$.simpleDialog();
</script>

Custom Title and description

$.simpleDialog({
  title:"Alert Dialog",
  message:"Alert Message"
});

With Callback

<script type="text/javascript>
$.simpleDialog({
    onSuccess:function(){
        alert("You confirmed");
    },
    onCancel:function(){
        alert("You cancelled");
    }
});
</script>
Jithin Vijayan
  • 307
  • 5
  • 19
  • 6
    Welcome to Stack Overflow! While links are great way of sharing knowledge, they won't really answer the question if they get broken in the future. Add to your answer the essential content of the link which answers the question. In case the content is too complex or too big to fit here, describe the general idea of the proposed solution. Remember to always keep a link reference to the original solution's website. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Jul 26 '18 at 08:03