Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - How to pass dynamic data in bootstrap modal?

I am trying to achieve the following:

I have a button :

<button id= "<dynamicid>" type="button" class="btn btn-danger btn-sm pull-right" data-toggle="modal" data-target="#mymodal">Open</button>

The id attribute changes everytime. Now clicking this button opens up a modal. What I am trying to achieve is get this dynamic id into the modal which opens up.

Here is the full modal:

<div class="modal fade" id="mymodal" data-placement="right" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header" style="padding: 4%; background-color: white; color: #6A6A6A; font-family: 'Crete Round', serif;">
        <input type="submit" class="btn btn-primary btn-sm" value="submit"/>
        <div class="modal-footer">
        </div>
      </div>      
    </div>
</div>
</div>

Any suggestions on this would be of great help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you didn't got really specific on what you want to do with the ID here an example on how it could be done:

$('#mymodal').on('show.bs.modal', function(e) {
    $(this).find('.modal-body').text(e.relatedTarget.id);
});

Example


Reference:

bootstrap - modal events

$('#mymodal').on('show.bs.modal', function(e) {
  var id = $(this).find('.modal-body').text(e.relatedTarget.id);
  if(id) console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<button id="whateverID" type="button" class="btn btn-danger btn-sm pull-right" data-toggle="modal" data-target="#mymodal">Open</button>
<div class="modal fade" id="mymodal" data-placement="right" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header" style="padding: 4%; background-color: white; color: #6A6A6A; font-family: 'Crete Round', serif;">
        Header

      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
      </div>
    </div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...