jquery read keys from type object - javascript

I am trying to implement Modal in bootstrap 5. I am following the link http://jsfiddle.net/341tfz8j/1/ . I have changed all his bootstrap 4 references such as data-toggle to data-bs-toggle and data-target to data-bs-target.
Below is my function:
$(function(){
$('#myModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show.bs.modal', function(){
Line 1 console.dir($(this).data()); //see the image below
Line 2 console.log('Type of variable '+ typeof mydata); /this is object
console.log($(this).data('myrow')); //this is undefined
});
$(".table-bordered").find('tr[data-bs-target]').on('click', function(){
$('#myModal').data('myrow', $(this));
Line 3 console.dir($('#myModal').data('myrow')); // I am able to get the row here
});
});
When I click on the row of my table, I am able to read the entire row and store it inside the modal.data. as 'myrow'. I am even able to read the key back and get the output (Line 3)
Now i am trying to access the same data inside show method. Below is the image for Line 1
Line 2 : shows that the variable is of type object
Line 3: When I try to read it, I get undefined even though i am able to see 'myrow' key as shown in the fig.
I want to know how can i access they 'myrow' key which is stored inside the object. I have tried below and both are undefined.
$(this).data('myrow')
$(this).data.myrow
My html
<div id="myModal" class="modal hide fade " >
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" data-bs-dismiss="modal">×</button>
</div>
<div class="modal-body">
<h1> content goes here</h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">cancel</button>
</div>
</div>
</div>
</div>

Since $(this).data() returns an object, you may access myrow property using
$(this).data().myrow

Related

Changing data in bootstrap modal

I'm working on jeopardy game where I pass questions into a bootstrap modal based on the button clicked. The button has an attribute data-num, (the index in the array of questions), which is used to to change the title in the modal. It also passes this index as an attribute data-num to the reveal answer button, which, when clicked, will change modal title to the answer.
This works for the first question, but when I click on the second question, the proper question loads, but the answer to the first question loads when I click the getanswer button, even though the proper index shows up in inspect element under button data-num.
What am I doing wrong?
var questions = [{
prompt: "What generic data type should we use when we want to use varying data types for a variable?",
correctAnswer: "Object",
},
{
prompt: "Rewrite the following Javascript statment in C#: var flag = true ",
correctAnswer: "bool flag = true"
},
{
prompt: "double num1 = 9.34534910;\n int num2= (int)num1;\nSystem.Console.WriteLine(num2);",
correctAnswer: "9"
}
];
function showQuestion(event, $modal) {
var button = $(event.relatedTarget);
var num = parseInt(button.data('num'));
var question = questions[num];
$modal.find('.modal-title').text(question.prompt);
$modal.find('.modal-body button').attr('data-num', num)
}
$("#myModal").on('show.bs.modal', function(event) {
showQuestion(event, $(this));
}
);
$("#myModal").on('hidden.bs.modal', function() {
$('#myModal').removeData('bs.modal');
}
);
$("#getanswer").click(function() {
var num = ($(this).data('num'));
console.log(num)
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bs-example">
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="modal-title" data-answer="">Modal Window</p>
<button id="getanswer" type="button" data-num="" class="btn btn-primary clickable">Reveal answer</button>
</div>
</div>
</div>
</div>
<div class="question">
<button type="button" class="btn btn-info gridbtn ten" data-toggle="modal" data-target="#myModal" data-num="0">$10</button>
</div>
<div class="question">
<button type="button" class="btn btn-info gridbtn fifty" data-toggle="modal" data-target="#myModal" data-num="1">$50</button>
</div>
</div>
Use this (on the #getAnswer click event):
var num = ($(this).attr('data-num'));
instead of
var num = ($(this).data('num'));
Perhaps since you set the value with attr, it also works to retrieve it that way.
It DOES seem like your way should work, but this is what I found through trying stuff.

Hide a dynamic element function on.('hide')

I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?
Thanks
function openModalFromUrl(modal_url, close_function = function(){}) {
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
data: {
'_token': token,
},
url: modal_url,
type: 'POST',
success: function(html) {
// create a new modal div
var modal = document.createElement("div");
$(modal).addClass('modal fade');
$(modal).attr( "role", "dialog" );
$('body').append(modal);
// place response in the modal
$(modal).html(html)
// open the modal
$(modal).modal('show');
// THIS FIRES IMMEDIATELY
$(modal).on('hide', window[close_function]() );
},
error: function() {
bootbox.alert('Error');
}
});
}
The issue is in this line :-
$(modal).on('hide', window[close_function]() );
Change it to :-
$(modal).on('hide', window[close_function] );
Explanation :-
In JavaScript when we provide a function as a reference, we use it's name without any parenthesis
i.e. 'my_func' not 'my_func()'
As 'my_func()' give the result of the function as reference not the function itself.
So just remove the parenthesis and your problem is solved.
According to the documentation you should use hidden.bs.modal event. Also no need in checking the window object for the function, just pass it.
$('#myModal').modal('show');
var close_function = function () {
console.log('closed');
}
$('#myModal').on('hidden.bs.modal', close_function);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" id='myModal' abindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Thank you to all for your answers. I have found the solution.
As the modals were dynamically generated i had to change the call to:
$('body').on('hide.bs.modal', modal, window[close_function] );
Now it works like a charm. Thanks again to everyone!

How to define $var only if parents('.class').attr('id') exists?

Here is my code:
<div class="superBlock" id="blabla">
<a class="watch"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs" role="group">
<a type="button" class="btn btn-info info" data-toggle="modal" data-target="#myModal">Information</a>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-footer">
<a type="button" class="btn btn-success watch" data-dismiss="modal">Watch</a>
</div>
</div>
</div>
</div>
$('.info').click(function() {
var $watchID = $(this).parents('.superBlock').attr('id');
});
$('.watch').click(function() {
if($(this).parents('.superBlock').attr('id') != "") {
var $watchID = $(this).parents('.superBlock').attr('id');
}
alert($watchID);
});
What I'd like to do is to set the $watchID to the .superBlock's ID whether I click on the .watch button or on the .info button.
And I get $watchID is "undefined" when I click on the modal watch button after clicking on the info button.
And I'd like the $watchID to keep on being set to the .superBlock's ID if the $(this).parents('.superBlock').attr('id') is undefined. So the $watchID not to change to the undefined $(this).parents('.superBlock').attr('id').
What should I do? Is this only about syntax? If so, how should I change this?
This HTML divs are repeating with different IDs, that's why I can't just set the ID to "blabla".
To tell if a selector matches anything, check the length of the jQuery object.
var superblock = $(this).closest(".superBlock");
if (superblock.length > 0) {
$watchID = superblock.attr('id');
}
Also, if you want the $watchID variable to persist between calls, it should be declared outside the functions. Your variable is local to each function, so it gets discarded when the function returns.
And since you just want the closest parent with that class, use .closest() rather than .parents(), which searches the entire DOM hierarchy for multiple matches.

Angular-Strap Modal Does Not Load Template

For some reason the modal box works just fine but it does not load any templates I specify.
My Controller has this code;
var brnSearchModal = $modal({ scope: $scope, template: "app/rrn/searchBrn.html", contentTemplate: false, html: true, show: false });
$scope.showModal = function () {
brnSearchModal.$promise.then(brnSearchModal.show);
};
My HTML looks like this;
<button data-ng-click="showModal()" type="button" class="btn btn-info" data-animation="am-fade-and-slide-top">
BRN Lookup
</button>
And my template is in a file and looks like this;
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title" ng-bind="title">Hello, World!</h4>
</div>
<div class="modal-body" ng-bind="content">Lorem ipsum dolor.</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>
</div>
</div>
</div>
</div>
There is no error everything seems to be working fine but the template does not load. If I debug angular-strap at one point the template is loaded but then disappears in and leaves a blank modal.
Remove ng-show="title", ng-bind="title" from the template.
Try adding the bs-modal attribute: see examples
<button data-ng-click="showModal()" type="button" class="btn btn-info" data-animation="am-fade-and-slide-top" bs-modal="brnSearchModal">
BRN Lookup
</button>
Otherwise use the data-template attribute directly without using the JS to show the modal:
<button type="button" class="btn btn-info" data-animation="am-fade-and-slide-top" data-template="app/rrn/searchBrn.html" bs-modal="modal">
BRN Lookup
</button>
I think when you put bs-modal="modal" modal is somehow pre-defined in the angular-strap library.
you should remove ng-show="title" , ng-show="content" or ng-bind="title" from the template. You should make sure that the template has no ng-show.
I know it is an old question, but in case others are looking for a solution to the same problem. I found I had to explicitly set templateUrl to falsy when setting template to an html string

jquery modal: closing a modal and then having it available as a clickable option

I been scratching my head on this one for a while.
Writing a plugin in grails that calls on bootstrap-mini.js and most of its css. Everything works fine. The issue I am having is I have a remote form which onComplete runs java script:
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListModal/_modalcreate.gsp
<g:javascript>
function ${controller}CloseModal() {
var myClone=$('#BuildModal${id}').clone();
$('#BuildModal${id}').dialog().dialog('close');
$(".modal-backdrop").hide();
$('body').removeClass('modal-open');
//var myCloner = myClone.clone();
$('#${divId}1').hide().append(myClone);
//$('body').append(myClone);
<g:if test="${!disablecheck.equals('true') }">
var controller="${controller }";
var divId="${divId }";
$.get('${createLink(controller:"MailingListEmail", action: "getAjaxCall")}?ccontroller='+controller+'&divId='+divId,function(data){
$('#${divId}').hide().html(data).fadeIn('slow');
});
</g:if>
}
</g:javascript>
The bits at the top of the function is all the things I have tried so far.
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListEmail/contactclients.gsp
<div class="tbutton">
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender">
New Sender?</button>
<div id="mailerSenders1">
<g:render template="/mailingListModal/modalcreate" model="[title:'Add Senders Email', controller: 'mailingListSenders', callPage: 'form' , divId: 'mailerSenders', id: 'SENDERS' ]" />
</div>
And finally modelForm which is included on the top of the modalcreate.gsp (now shown)
<div class="modal fade" id="BuildModal${id}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<g:formRemote id="${controller}" name="urlParams" class="form-horizontal" url="[controller:controller, action:'save']"
update="BuildModal${id}" onComplete="${controller}CloseModal()"
>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>${title }</h3>
</div>
<div class="modal-body">
<div class="form-group">
<g:render template="/${controller }/${callPage }"/>
<g:submitToRemote class="myformsubmit" url="[controller:controller, action:'save']" update="BuildModal${id}" onComplete="${controller}CloseModal()" value="Create" />
</div>
</div>
</g:formRemote>
</div>
</div>
</div>
</div>
So it is a remote Form that submits can calls the above CloseModal
The question is when I Close this how do I make it available again when the user clicks the button to create new email ?
After adding all the cloning at the top of java script the only difference I was able to make was to make it display the backdrop on 2nd click so it went black on 2nd click but did not show up the modal content.
ok got it working by doing this:
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender"
Now adding
onClick="runCheck()"> .....
<g:javascript>
function runCheck() {
$('#mailerSenders1').show();
}
</g:javascript>
That seems to work fine, it now loads up the page, just to add when I did body it just loaded it up again from the commented out attempts, modal.hide etc did not work and the hide attempts just showed it up under some other layers of the same page.. anyways this works fine now. sorry

Categories