Reputation: 109
I have a button with some data attributes. When I click it, a modal is shown. In this modal I have a button that updates DB and closes the modal. I need to change the data attribute in the button I clicked on to show the modal. Anyone have suggestions? See last line of code. e.relatedTarget is not working here.
$(document).on('show.bs.modal','#myModal', function (e) {
$('#textareaID').val($(e.relatedTarget).data('text')); //the data attribute used here I need to change later
$('#listID').val($(e.relatedTarget).data('listid'));
});
$(document).on('hide.bs.modal','#myModal', function (e) {
//Clearing values before next use of modal
$('#textareaID').val('');
$('#listID').val('');
});
$(document).on('click', '#btnSave', function(e) {
var id = $('#listID').val();
var text = $('#textareaID').val();
//code here to update DB
//Now need to set the data-text attribute value to "text" variable.
$(e.relatedTarget).data('text', text); // NOT WORKING!
}
Upvotes: 2
Views: 1174
Reputation: 1984
Something like this should work, add a class to the button that opened the modal, then when saving the modal just replace the data-attribute and remove the 'opened' class.
var modal = $('.modal');
var btn = null;
$(document).on('click', '.open-modal', function(e) {
btn = $(this);
btn.addClass('opened-modal');
modal.show();
modal.find('.modal-header').append('Clicked: ' + $(this).html());
$(document).on('click', '#btnSave', function(e) {
var text = $('#myInput').val();
// code here to update DB
// Now need to set the data-text attribute value to "text" variable.
btn.attr('data-text', text);
btn.removeClass('opened-modal');
modal.hide();
});
$(document).on('click', '#btnClose', function(e) {
var btn = null;
modal.hide();
});
});
.modal {
display: none;
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="open-modal" data-text="button">one</button>
<button class="open-modal" data-text="button">two</button>
<button class="open-modal" data-text="button">three</button>
<button class="open-modal" data-text="button">four</button>
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal</h5>
<input id="myInput" type="text">
</div>
<div class="modal-footer">
<button type="button" id="btnSave" data-dismiss="modal">add-attr</button>
<button type="button" id="btnClose" data-dismiss="modal">close</button>
</div>
</div>
</div>
</div>
Upvotes: 1