Load modal with custom data-id

2020-02-26 14:19发布

问题:

I have an issue with one of my website.

I have some list links like this:

<ul>
  <li><a data-toggle="modal" data-target="#myModal" data-id="10">Room 10</a>
  <li><a data-toggle="modal" data-target="#myModal" data-id="20">Room 20</a>
</ul>

On my #myModal, I want the form appears to edit info. So I passed the data-id, which is the id into my database.

HTML is the following:

<div class="modal modal-open" id="myModal">
  <form class="modal-form form-horizontal">
    <div class="modal-header">
      <h3>Room #xx</h3>
    </div>
    <div class="modal-body"> <input name="roomNumber" type="text" value="xx">
    </div>
    <div class="modal-footer">
      <button type="submit" class="btn btn-primary">Save</button>
    </div>
  </form>
</div>

My question, is how can I load the rooms infos from my db into the #myModal window ?

Step by Step:

  1. I click on the Edit room link.
  2. The modal loads infos from the db.
  3. I can change info.
  4. I save the form.
  5. The modal close.

Thanks a lot.

回答1:

Assuming an element in your modal with the ID roomNumber, such as:

<p>Your room number is: <span id="roomNumber"></span>.</p>

you'd do something like this to populate it:

var myRoomNumber;

$('#rooms li a').click(function() {
   myRoomNumber = $(this).attr('data-id'); 
});

$('#myModal').on('show.bs.modal', function (e) {
    $(this).find('.roomNumber').text(myRoomNumber);
});

http://jsfiddle.net/isherwood/Yafb5

There's probably a way to simplify this by grabbing the click target inside the show function and getting the id there, but it's escaping me at the moment.


Update: Found it:

$('#myModal').on('show.bs.modal', function (e) {
    var myRoomNumber = $(e.relatedTarget).attr('data-id');
    $(this).find('.roomNumber').text(myRoomNumber);
});

http://jsfiddle.net/isherwood/Yafb5/4



回答2:

$( ".button").on("click", function(event){
/* if you want to use the same modal, you must unbind() actions because bootstrap 
   remember olders actions on Modal element */

$( "#MyModal" ).unbind();
var btn = $(this);
var id = $(this).data("id"); /* "data-id" attribute in html */
$.ajax({
 type: 'POST',
 url: content_direct_delivery_in_html,
 data: { id: id },
success: function(html) {
 $('#MyModal').modal().on('shown.bs.modal', function (e) {
  $("#MyModal_body").html(html);
 });
}

Your Html like this :

<button class="btn btn-success btn-sm button" data-id="<?php echo $BDD['id']; ?>" data-toggle="modal" data-target="#MyModal">
click me
</button>