I tried to update an existing data-target
with a data-target="#testModal1"
to point to the #testModal2
modal using jquery .data
, but even after the data attribute change it still is linked to #testModal1
//Jquery:
$('#testButton').data('target', '#testModal2')
<!-- HTML: -->
<button id='testButton' data-toggle="modal" data-target="#testModal1">
Test
</button>
<div class="modal fade" id="testModal1" tabindex="-1" role="dialog" aria-hidden="true" style='display:none'>
<div class="modal-dialog">
<div class="modal-content">
Testing Testing 1
</div>
</div>
</div>
<div class="modal fade" id="testModal2" tabindex="-1" role="dialog" aria-hidden="true" style='display:none;'>
<div class="modal-dialog">
<div class="modal-content">
Testing Testing 2
</div>
</div>
</div>
data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components. The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed. Modal Example Code from BS3: <!--
You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form. You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.
Just add data-toggle="collapse" and a data-target to element to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element. If you'd like it to default open, add the additional class in.
Let's look in the jQuery documetation what .data()
is:
.data()
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
.data( key, value )
Description: Store arbitrary data associated with the matched elements.
key
Type:
String
A string naming the piece of data to set.
value
Type: Object
The new data value; it can be any Javascript type including Array or Object.
Using $('#testButton').data('target','#testModal2')
you will not modify the data-target
attribute but you will store the string "#testModal2"
in "target"
field. Then $('#testButton').data('target')
will return "#testModal2"
.
It's true that .data('key')
can be used to return the data-key
attribute value. But you cannot set it using .data('key', 'newValue'
).
To set an attribute value the most common and easy way is to use .attr()
method.
So, the answer is easy: change data
in attr
and use data-target
instead of target
:
$('#testButton').attr('data-target','#testModal2');
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With