ChatGPT解决这个技术问题 Extra ChatGPT

Passing data to a bootstrap modal

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

We should update the code to a recent one, with bootstrap5 and with pure JS as option besides jquery.

m
mg1075

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');
});

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.
@LeonCullens - I've updated the fiddle and the code. Does it work the way you want now?
Good answer - but is the modal('show') required? Seems like the data-toggle="modal" on the links would take care of that.
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 - $(this).data() is part of jQuery. api.jquery.com/data/#data-html5
L
LostInComputer

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/


$(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?
@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.
replacing $(this) with $(e.relatedTarget) works great
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...
This one should be the accepted answer, I tried $(this) but didn't work, replacing it with $(e.relatedTarget) got the job done. Thanks!
J
J W

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);
  })
});

you can use !! $(this).data('id') instead of typeof $(this).data('id') !== 'undefined'
K
Kamil Kiełczewski

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 } Open


V
VTStampede

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>

p
phil

Your code would have worked with correct modal html structure.

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


E
Ehsan Ahmadi

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')
    // ...
    // ...
})



s
shaurya airi

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

H
Herbert Van-Vliet

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!
U
Unicco

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 )


D
Deyson

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') 
  })
})

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
M
MaieonBrix

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);
     })
    });

d
davidauza.engineer

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");
})

J
James Osguthorpe

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>

J
Jithin Vijayan

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>

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?