Erik Nucibella
Erik Nucibella

Reputation: 121

How to click a button inside a modal after opens it?

I really want to know, how can I click a button inside a Bootstrap modal after I've open it by clicking its link:

<a href="#" data-toggle="modal" data-target="#myid">

Buttons have ids', so I think I can click the button using js, but I don't really know how to deal with this.

Could I use a function such as $("#buttonid").click(); in the data-target after the modal call?

I tried with no results. Any help would be appreciate

Here is the button code:

<button type="submit" id="buttonid" name="Profile" href="#">

Upvotes: 2

Views: 10055

Answers (2)

Anil  Panwar
Anil Panwar

Reputation: 2622

$('#myModal').on('shown.bs.modal', function (event) {
 $("#newBtn").trigger("click");  
});

 $("#newBtn").on("click",function(){
 alert("button inside modal clicked");
 
 })
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" 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">
   You can make the button hidden by adding class hidden to button.
       <button type="button" id="newBtn" class="btn btn-sm btn-info">clicked on modal open</button>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

Upvotes: 3

Shintu Joseph
Shintu Joseph

Reputation: 962

Call the trigger on the modal shown event

$('#myid').on('shown.bs.modal', function () {
   $("#buttonid").trigger('click');
});    

Upvotes: 0

Related Questions