Stangn99 Stangn99 - 4 months ago 27
jQuery Question

Dynamically set HREF value within modal window (bootstrap/jquery)

I'm trying to figure out how to add change the value of an HREF within a modal based on the various links that users click on to activate the modal.

For instance I have 3 links which open the exact same modal window:

<a href="#" target="_blank" data-toggle="modal" data-target="#mymodal">Modal-1</a>
<a href="#" target="_blank" data-toggle="modal" data-target="#mymodal">Modal-2</a>
<a href="#" target="_blank" data-toggle="modal" data-target="#mymodal">Modal-3</a>


The information contained in the modal window is the same for all 3, but the tag within the modal window will redirect to a different location based on the link the user clicked on to open the modal.

Here's the modal markup:

<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
<h1 class="modal-title">My Modal Window</h1>
</div>
<div class="modal-body">
<p>My copy goes here</p>
</div>
<div class="modal-footer">
<a id="closemodal" href="DEPENDS ON LINKED CLICKED TO OPEN MODAL" class="btn btn-primary" target="_blank">GO</a>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>

Answer

You can use jQuery attr(key, value) to change href of hyperlink.

<a href="#" target="_blank" data-toggle="modal" data-target="#mymodal" data-link="google.com">Modal-1</a>

$('a').click(function() 
{
    $('#closemodal').attr('href', $(this).data('link'));
});

https://jsfiddle.net/kaofgend/3/

Comments