I am trying to pass a value I have for the data-id in a button to a modal form. My code is below:
Script:
<script type="text/javascript">
$(document).on("click", "open-exampleModal", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val($(this).data('id'));
});
</script>
Button to open modal:
<div class="grid-cell" >
<span>
<button type="button" id="btnShowModal" class="btn btn-link btn-square-md" data toggle="modal" data-target="#exampleModal" data-id="B1"></button>
</span>
</div>
Modal:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalbody">
<p>some content</p>
<input type="text" name="bookId" value=""/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
When I click the button to open the modal it opens the modal successfully, however, it does not populate the input with the value from the data-id. I took the code from another answer from awhile back and wondering if something potentially has updated since then.
2
Answers
This selector doesn’t match any element in your HTML:
So no value is populated:
But this one does:
Example:
You are doing a mistake in script. Update the script:-
Hope it will be helpful.