Passing data to a bootstrap modal
Asked Answered
E

16

621

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?)

Enroll answered 16/5, 2012 at 21:19 Comment(2)
We should update the code to a recent one, with bootstrap5 and with pure JS as option besides jquery.Shrink
can you pass the whole model without jquereySisco
S
608

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');
});
Savona answered 17/5, 2012 at 12:20 Comment(9)
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.Enroll
@LeonCullens - I've updated the fiddle and the code. Does it work the way you want now?Savona
Good answer - but is the modal('show') required? Seems like the data-toggle="modal" on the links would take care of that.Cocktail
@Cocktail - Correct! The data-toggle="modal" does make the $(...).modal('show') call superfluous. jsfiddle.net/55ZWe/1Savona
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.Lambrecht
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! =PEngraving
@Engraving - $(this).data() is part of jQuery. api.jquery.com/data/#data-html5Savona
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?Shrink
@Shrink - 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.Savona
H
436

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/

Hofuf answered 31/7, 2014 at 13:28 Comment(4)
$(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?Subsistence
@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.Burkhard
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...Epiclesis
This one should be the accepted answer, I tried $(this) but didn't work, replacing it with $(e.relatedTarget) got the job done. Thanks!Cyclopentane
M
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);
  })
});
Memorabilia answered 14/2, 2014 at 0:50 Comment(1)
you can use !! $(this).data('id') instead of typeof $(this).data('id') !== 'undefined'Pareu
B
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>
Buehler answered 10/4, 2019 at 14:35 Comment(0)
C
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>
Caldeira answered 6/4, 2017 at 15:28 Comment(0)
C
12

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 )
Clinical answered 21/2, 2022 at 11:14 Comment(1)
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!Battaglia
N
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>
Nervine answered 7/6, 2017 at 13:21 Comment(0)
A
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')
    // ...
    // ...
})


Angola answered 3/5, 2020 at 7:46 Comment(0)
C
7

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 )

Cicala answered 3/9, 2020 at 16:7 Comment(1)
Perfect for what I needed :)Citarella
G
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
})
Gully answered 11/10, 2020 at 6:55 Comment(0)
D
3

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>
Detrude answered 17/12, 2020 at 21:27 Comment(0)
P
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') 
  })
})
Playwriting answered 4/5, 2016 at 4:12 Comment(1)
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 dialogBlythe
S
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");
})
Stanza answered 7/1, 2021 at 20:29 Comment(0)
C
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);
     })
    });
Cherenkov answered 4/3, 2020 at 22:11 Comment(0)
D
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>
Daumier answered 17/11, 2022 at 1:46 Comment(0)
V
-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>
Volatilize answered 26/7, 2018 at 7:45 Comment(1)
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?Pizzicato

© 2022 - 2024 — McMap. All rights reserved.