Reputation: 1035
I'm creating some modals as follow:
<button type="button" class="btn btn-primary student" data-toggle="modal" data-target="#myModal" data-id={{item.st_number}}>
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I want to change modal ids to button data-id field with the following script:
$(document).on("click", ".student", function() {
var stid = $(this).data('id');
$(".modal-header h5").html(stid);
$(this).find('.myModal').text(stid);
});
changing modal header works, but modal name is not changed.
Upvotes: 2
Views: 916
Reputation: 1195
The below script xhanges you modal ID as well, try it:
$(document).on("click", ".student", function() {
var stid = $(this).data('id');
$(".modal-header h4").html(stid);
$('.modal').attr('id', 'desired_id');
});
Upvotes: 0
Reputation: 22323
You can't use find()
like that because .find()
method allows us to search through the descendants of these elements in the DOM tree . Use next()
with find()
to get element and change text.
$(document).on("click", ".student", function() {
var stid = $(this).data('id');
$(this).next('div').find(".modal-header h4").text(stid);
$(this).next('div.modal').attr('id', stid);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary student" data-toggle="modal" data-target="#myModal" data-id={{item.st_number}}>
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Upvotes: 1
Reputation: 979
your jQuery is wrong. there are not any h5
tag in HTML within .modal-header
class.
you can try this
$(document).on("click", ".student", function() {
var stid = $(this).data('id');
$(".modal-header h4").text(stid);
});
Upvotes: 0