Pass Data ID to Bootstrap Modal from Hyperlink
Learn how to pass a unique data-id from a link to a hidden input in Bootstrap modal using show.bs.modal event and relatedTarget. Fix common issues with data-toggle, BS4/BS5 examples, and troubleshooting for reliable dynamic modals.
You can keep the link as a normal anchor (or a button) and let Bootstrap handle the modal opening with the data-toggle="modal" and data-target attributes.
Then use a click handler to copy the data-id value into the hidden input before the modal is shown.
<!-- Link -->
<a href="#"
class="open-AddBookDialog"
data-toggle="modal"
data-target="#addBookDialog"
data-id="@book.Id"
title="Add this item">
Add
</a>
<!-- Modal -->
<div class="modal hide" id="addBookDialog">
<div class="modal-body">
<input type="hidden" name="bookId" id="bookId" value="">
</div>
</div>
$(function () {
// Use event delegation in case the links are added dynamically
$(document).on('click', '.open-AddBookDialog', function (e) {
e.preventDefault(); // keep the link from navigating
var id = $(this).data('id'); // read the data-id
$('#bookId').val(id); // set the hidden input
// Bootstrap will automatically show the modal because of data-target
});
});
Why this works
data-toggle="modal"+data-target="#addBookDialog"tells Bootstrap to open the modal when the link is clicked.- The click handler runs before Bootstrap shows the modal, so the hidden input is populated with the correct ID.
e.preventDefault()stops the anchor from navigating to#, which would otherwise scroll to the top of the page.
With this setup the modal opens correctly and the hidden input contains the data-id value you need.
To pass a unique data-id from a hyperlink to a hidden input in a bootstrap modal, add data-toggle="modal" (or data-bs-toggle in BS5) and data-target to your link, then capture the value in the modal’s show.bs.modal event using e.relatedTarget. This lets Bootstrap handle opening the modal naturally while populating #bookId reliably—no manual clicks or preventDefault needed. Works seamlessly with Razor @book.Id in ASP.NET lists.
Contents
- How to Pass Data ID from Hyperlink to Bootstrap Modal
- Common Issues with data-toggle=“modal” and data-id
- Using the show.bs.modal Event to Populate Modal Input
- Complete HTML and JavaScript Examples for Bootstrap Modal
- Bootstrap 4 vs Bootstrap 5 Modal Data Passing Differences
- Troubleshooting: Modal Not Opening or Data Not Passed
- Best Practices and Alternatives for Dynamic Modals
- Sources
- Conclusion
How to Pass Data ID from Hyperlink to Bootstrap Modal
Ever clicked a link in a product list expecting a bootstrap modal to pop up with the right details, only to see an empty form? You’re not alone. The fix boils down to Bootstrap’s built-in events. Ditch manual modal calls like $('#myModal').modal('show')—they often miss the trigger context.
Instead, tag your anchor (or button) with data-toggle="modal" data-target="#yourModalId" data-id="@book.Id". Bootstrap spots the attributes and fires the modal. Then, hook into show.bs.modal to grab the ID from the triggering element.
Why this over a plain click handler? The event runs right before display, ensuring data flows perfectly. Here’s the essence:
<a href="#"
data-toggle="modal"
data-target="#addBookDialog"
data-id="@book.Id"
class="btn btn-primary">
Add Book
</a>
Quick test: Does your modal have class="modal fade"? Add it if missing—Bootstrap expects it.
Common Issues with data-toggle=“modal” and data-id
Data-toggle=“modal” setups break fast. Href jumps to the top of the page? That’s the anchor # fighting Bootstrap. Solution: Swap to data-target="#modalId" and drop href="#modalId".
Empty data-id in the input? Often because you’re reading it too late—after the modal shows—or jQuery’s .data() chokes on Razor output. @book.Id renders fine as data-id="123", but confirm with browser dev tools.
Dynamic lists (like ASP.NET @foreach)? Event delegation helps, but show.bs.modal sidesteps classes entirely. Seen “modal not opening”? Check for duplicate IDs or missing Popper.js in BS5.
And buttons vs links? Buttons shine here—no preventDefault drama.
Using the show.bs.modal Event to Populate Modal Input
This is the gold standard, straight from Bootstrap docs and top Stack Overflow answers. The show.bs.modal event passes relatedTarget—your link!—so you snag the ID effortlessly.
$('#addBookDialog').on('show.bs.modal', function(event) {
var bookId = $(event.relatedTarget).data('id');
$(this).find('#bookId').val(bookId);
});
See? event.relatedTarget points to the clicked <a>. Set the hidden input inside the modal context with $(this).find(). No globals, no timing issues.
What if multiple modals? Namespace events: 'show.bs.modal.data-api'. Cleaner than class-based clicks.
Pro tip: Log console.log(bookId) first. Empty? Inspect data-id attribute—maybe it’s data-book-id for camelCase safety.
Complete HTML and JavaScript Examples for Bootstrap Modal
Ready to copy-paste? Here’s a full Razor-friendly snippet for a book list. Tested in BS4/5.
<!-- In your list, e.g., @foreach(var book in Model.Books) -->
<a href="#"
data-toggle="modal"
data-target="#addBookDialog"
data-id="@book.Id"
class="btn btn-sm btn-outline-primary"
title="Edit Book">
Edit
</a>
<!-- Modal (once, outside loop) -->
<div class="modal fade" id="addBookDialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Book</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="bookId" name="bookId" value="">
<form asp-action="Edit">
<!-- Other fields -->
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
</div>
JavaScript (document ready or after Bootstrap loads):
$(document).ready(function() {
$('#addBookDialog').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget).data('id');
$('#bookId', this).val(id); // Scoped to modal
});
});
Fires on click, modal opens loaded. Swap data-toggle to data-bs-toggle for BS5.
Bootstrap 4 vs Bootstrap 5 Modal Data Passing Differences
BS4 uses data-toggle="modal" data-target="#id". BS5? data-bs-toggle="modal" data-bs-target="#id". Events stay show.bs.modal, but include Popper for positioning.
BS5 drops jQuery reliance—pure JS possible:
const myModal = document.getElementById('addBookDialog');
myModal.addEventListener('show.bs.modal', (event) => {
const bookId = event.relatedTarget.dataset.id;
myModal.querySelector('#bookId').value = bookId;
});
Migration tip: Update attributes, add BS5 CDN. BS4 docs confirm the event API didn’t change much.
Stuck on BS3? Same events, but add hide class manually.
Troubleshooting: Modal Not Opening or Data Not Passed
Modal ghosts you? Console errors: “Bootstrap’s JavaScript requires jQuery”? Load jQuery before Bootstrap JS.
Data blank? data('id') vs attr('data-id')—use .data(). Razor ints? data-id="@book.Id.ToString()".
No open on dynamic content? Delegation: $(document).on('show.bs.modal', '.modal', function... but target specific modals.
Conflicts? Multiple data-target? Unique IDs only. BS5 backdrop issues? data-bs-backdrop="static".
Test: JSFiddle demo from SO works every time.
Best Practices and Alternatives for Dynamic Modals
Keep IDs unique. Use one modal, populate via events—scales for 100s of links. Security? Server-validate bookId.
Alternatives: No-jQuery with HTMX for AJAX modals. Or custom divs with display: block—lighter but loses animations.
For forms, POST the ID via fetch inside the event. Profile tip: Debounce if mega-lists.
Future-proof: BS5 native JS. Questions? Dev tools reveal all.
Sources
- Passing data to a bootstrap modal — Comprehensive Q&A with code examples and JSFiddle for data attributes in modals: https://stackoverflow.com/questions/10626885/passing-data-to-a-bootstrap-modal
- Bootstrap Modal Documentation — Official guide on events like show.bs.modal and data attributes for dynamic content: https://getbootstrap.com/docs/5.3/components/modal/
- Bootstrap 4 Modal Components — BS4 specifics on data-toggle and relatedTarget for passing data: https://getbootstrap.com/docs/4.6/components/modal/
- Pass Data Bootstrap Modal Data Attributes — Tutorial with click handlers and event examples: https://sqlpey.com/javascript/pass-data-bootstrap-modal-data-attributes/
- Pass data attribute to modal bootstrap — Working BS4 demo using show.bs.modal event: https://stackoverflow.com/questions/45731337/pass-data-attribute-to-modal-bootstrap/45733078
Conclusion
Mastering bootstrap modal data passing with show.bs.modal and relatedTarget eliminates guesswork—your @book.Id lands in #bookId every time, modals open smoothly. Ditch href hacks, embrace events for clean, scalable code. Whether BS4 lists or BS5 apps, this pattern just works. Experiment in a fiddle, and you’ll never chase empty fields again.
Give the link a data-target that points to the modal and let Bootstrap handle the opening. Hook into the modal’s show.bs.modal event to copy the id from $(e.relatedTarget).data('id') into the hidden input. This sets the value before the modal displays and works reliably without manual modal opening.
Add data-toggle="modal" data-target="#addBookDialog" data-id to the link. On the modal show.bs.modal event, set $('#bookId', this).val($(e.relatedTarget).data('id')). Bootstrap opens the modal via data-target, and the event captures the data from the trigger element.
Use the same show.bs.modal event approach to pass data attributes from the trigger link to the modal input field reliably.
Use data-bs-toggle="modal" data-bs-target="#addBookDialog" on the link with data-id. Listen to the show.bs.modal event on the modal: the relatedTarget property references the trigger element. Extract the ID with $(event.relatedTarget).data('id') and assign it to #bookId.val(id) before the modal shows.

