Putting 'document' vs 'the selector itself' in jQuery? - javascript

Guys I have 2 questions which is i think related in some ways I guess. First:
What is the difference between these two:
$(document).on('click','#someselector', function() {
//do something
});
vs this
$('#selector')on('click', function(){
/do something
});
Sometimes both works, sometimes it doesn't.
Number 2 question:
I created a jQuery UI dialog like this:
function this_dialog(id) {
$("#div-id-for-the-dialog").dialog({
autoOpen : false,
modal : true,
draggable : false,
width : 400,
buttons : [{
id : id,
text : 'Ok'
},{
text : 'Cancel',
click : function () {
$("#div-id-for-the-dialog").dialog('close');
}
}]
});
}
So as you can see, the id is passed to the function, many will call this dialog and pass a unique id to it. The id will then be assigned only to the Ok button.
So when i call this function to load a unique dialog:
add_section_complete_reopen_dialog('my-unique-dialog-id'); //passing the id
$('#div-id-for-the-dialog').html("I have a unique dialog now? ok?");
When i press ok with this code:
$(document).on('click','#my-unique-dialog-id', function () {
//Do some ajax call here
});
I get this JS error: TypeError: s is undefined
But the ajax is successful. I just want to know what that error is.
So when I say it is related to the first question is because when i replace the click code with this:
$('#my-unique-dialog-id').on('click', function () {
//Do some ajax call here
});
It doesn't work anymore.
Thanks

$(document).on('click', 'someselector', function() ...);
is delegation syntax. It allows you to bind a handler to elements that may not exist at the time that you execute the code. See:
Event binding on dynamically created elements?
$('someselector').on('click', function() ...);
only binds the handler to the element(s) matching the selector at the time you execute this code.

I marked the first answer correct because I know I did not put enough info on how to debug the second question, but In case someone might encounter the same error i had, I found out why. So when you initialize your jQuery UI dialog like this:
function this_dialog(id) {
$("#div-id-for-the-dialog").dialog({
autoOpen : false,
modal : true,
draggable : false,
width : 400,
buttons : [{
id : id,
text : 'Ok'
},{
text : 'Cancel',
click : function () {
$("#div-id-for-the-dialog").dialog('close');
}
}]
});
}
Make sure to include the click event of the buttons like this:
function this_dialog(id) {
$("#div-id-for-the-dialog").dialog({
autoOpen : false,
modal : true,
draggable : false,
width : 400,
buttons : [{
id : id,
text : 'Ok',
click : function () {
//include the click event, even if you have nothing to put here.
}
},{
text : 'Cancel',
click : function () {
$("#div-id-for-the-dialog").dialog('close');
}
}]
});
}

Related

Bootstrap-confirmation not respecting options

Just adding the bootstrap-confirmation extension for Bootstrap popover to some buttons on a project. I'm having issues with the options not being respected. I'm trying to get the popups to work as singletons and dismiss when the user clicks outside of them singleton and data-popout options, respectively - both set to true. I'm also not seeing any of my defined callback behavior happening.
I defined the options both in the HTML tags and in a function and neither works. Still getting multiple boxes and they don't dismiss as expected.
My JS is loaded after all other libraries and is in my custom.js file in my footer.
JS is as follows:
$(function() {
$('body').confirmation({
selector: '[data-toggle="confirmation"]',
singleton: true,
popout: true
});
$('.confirmation-callback').confirmation({
onConfirm: function() { alert('confirm') },
onCancel: function() { alert('cancel') }
});
});
An example of the box implemented on a button in my HTML is the following:
<a class="btn btn-danger" data-toggle="confirmation" data-singleton="true" data-popout="true"><em class="fa fa-trash"></em></a>
Any pointers would be appreciated. I even changed the default options in the bootstrap-confirmation.js file itself to what I want and still no luck.
Turns out I needed to rearrange a couple things to get this to work. I've left in the last_clicked_id etc stuff as I needed to add that to get the id value of what I'd just clicked.
// Product removal popup logic
var last_clicked_id = null;
var last_clicked_product = null;
$('.btn.btn-danger.btn-confirm').click(function () {
last_clicked_id = $(this).data("id");
last_clicked_product = $(this).data("product");
});
$('.btn.btn-danger.btn-confirm').confirmation({
singleton: true,
popout: true,
onConfirm: function () {
alert("DEBUG: Delete confirmed for id : " + last_clicked_product);
// TODO: Add AJAX to wipe entry and refresh page
},
onCancel: function () {
alert("DEBUG: Delete canceled for id : " + last_clicked_product);
}
});
I was a step ahead of myself with the callback logic which was not getting executed. Fixed by simply adding it to onConfirm: and onCancel: key values in the .confirmation() function. A bit of a RTFM moment there but this was unfortunately not very clear in the documentation.

Bootbox: Make the default button work with the ENTER key?

As the title suggests, I want to add the Enter key as an event handler for Bootbox.js. When you an alert() popup is called, you can press enter to dismiss it, but that is not the case with Bootbox.js. I do not know how to get access to the button inside Bootbox.js to add an event handler. Any suggestions?
In order for the button to take focus, it should be defined with the "btn-primary" class name:
className:
main: {
className: "btn-primary", ...
}
I see this post has no answer yet for case when user has focus in the form itself
Here's how to do it :
Code :
$(document).on("submit", ".bootbox form", function(e) {
e.preventDefault();
$(".bootbox .btn-primary").click();
});
bootbox.dialog({
title : "Title",
message : $("#templateWithForm").html(),
onEscape : true,
buttons :
{
success : {
label : "OK",
className : "btn-success btn-primary",
callback : function() {
// do something...
}
}
}
})
Explanation :
First bit of code will catch the "submit" event for all bootbox dialogs with forms in it and prevent the submit with preventDefault() it will then emulate a click on the button that has className : "btn-primary"
(Note that it's going to trigger a click to all bootbox dialogs so you might wanna change it for your use case if you have more than a dialog on the page at once)
Second bit of code is a simple dialog calling. Important parts are
onEscape : true if you want to close the dialog with Escape key
className : "btn-success btn-primary" btn-success can obviously be changed to fit your needs
Hope this helps the next person !
You can just add 'bootbox-accept' className for the button you want to click on enter key press.
Example:
bootbox.dialog({
title : "Title",
message : "Your Message",
onEscape : true,
buttons :
{
success : {
label : "OK",
className : "btn-success bootbox-accept",
callback : function() {
// do something...
}
},
cancel:{
label : "Cancel",
className : "btn-danger",
callback : function() {
// do something...
}
},
}
})
use btnclassName and assign "btn-primary as below in code
function ShowpopUp() {
bootbox.confirm({
size: "Large",
btnclassName: "btn-primary",
title: "Guests from outside your organization",
message: "The following recipients are from outside of the SPSG organization:<br> <br> "
+
getSelectedNonMembersEmails()
+ "<br> <br> Are you sure you would like to send it?",
callback: function (result) {
if (result === true) {
reportVm.currentPage(4);
}
else {
bootbox.hideAll();
}
}
});
}

Jquery not responding inside AJAX form results display

I've just started to really work in jquery and AJAX and for the most part I've seem to have the hang of it but this one little bit of code is not working.
I have a page that displays a summary of articles. When you click on the article name a popup window displays and the article information is show along with a X icon in the upper right hand corner that is to close the article window.
I'm handling the form processing via AJAX and it works great. The window pops up, all the proper information is displayed. The issue I am running into is the Close button function.
When you click on the close button, nothing happens. The jquery I have for it doesn't seem to respond. If I just use pure jquery/css the window appears and the close button works. If I handle the form with HTML/PHP it displays the window and the close button works.
Only when I handle the call via AJAX does the close button not respond and I am at a loss why this is.
Here is the simple jquery code for the close button:
$('.newsClose').click(function(){
$('#newsWindow').hide();
});
This is the AJAX call:
$(document).ready(function() {
$('#agentNewsForm').submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
data : $('#agentNewsForm').serialize(),
url : '/search/customer/agentNewsView.inc.php',
beforeSend : function() {
$('#processing').show();
},
error : function() {
$('#processing').hide();
$('#ajaxFormError').show();
},
// success callback
success : function (response) {
$('#processing').hide();
$('#newsWindow').html(response).show();
},
complete : function() {
$('#processing').hide();
},
timeout : 3000,
});
return false;
});
});
I'm sure it's something very simple that I am missing. Any thoughts?
$(document.body).on('click', '.newsClose' ,function(){
$('#newsWindow').hide();
});
See this SO:
Jquery event handler not working on dynamic content
Your code to close the window is only firing on document load, and your close button is inside #newsWindow, you can resolve this in one of two ways ...
$('#newsWindow>.content').html(response).show(); and keep your close button outside of the .content area.
or you can use the on method which will bind your close click on all new dom added to the document.
$(body).on('click', '.newsClose', function(e){ e.preventDefault; $('#newsWindow').hide(); });
Try this:
(function($){
var $newsWindow = $('#newsWindow');
$('body').on('click','.newsClose',function(e){
e.preventDefault();
$newsWindow.hide();
});
$('body').on('submit','#agentNewsForm',function(e){
e.preventDefault();
var $el = $(this);
var $process = $('#processing');
var $error = $('#ajaxFormError');
var _data = $el.serialize();
$.ajax({
type : 'POST',
data : _data,
url : '/search/customer/agentNewsView.inc.php',
beforeSend : function() {
$process.show();
},
error : function() {
$error.show();
},
success : function (response) {
$newsWindow.html(response).show();
},
complete : function() {
$process.hide();
}
});
});
})(jQuery);

how to call alloy ui on click function for all elements with same css class name

What I want is that I have few links like
sample Link 1 sample Link 2
and I want to call the static html when user clicks the link. For that I have written a code
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.popup-link').on('click',
function() {
var dialog = new A.Dialog({
bodyContent: 'Loading...',
centered: true,
title: 'Sample Popup Content',
width: 400,
height:600
}
).render();
dialog.plug(
A.Plugin.IO,
{
autoLoad: false,
uri: '/html/sample.html'
}
);
dialog.io.start();
});
});
but this does not work, it simply does not call the function when I click the link, I also tried this, but same thing
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.sample-popup').each(function() {
this.on('click', function(A){
.....
......
Any idea what is wrong here?
Finally I got why it was not working. I was using the same object "A" in the click function as well.
it should be like this: (have a look at the variable name event)
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.sample-popup').each(function() {
this.on('click', function(event){
.....
......
I don't know much about AUI but if you want to achieve same task using jQuery you can achieve like this
i.e
<script>
$(document).ready(function() {
$('.popup-link').click(function(){
alert($(this).text());
});
});
</script>
Or
Using Javascript
i.e
Link
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
HTH

AgilityJS Add and Remove Event

Good morning,
I try these days to make AgilityJS work, and i'm still stuck with these two naturals events : add and remove.
(function(window){
var Test = $$({
model : {},
view : {
format : '<div></div>'
},
controller : {
'create' : function(){
console.log('create');
},
'add' : function(){
console.log('add');
},
'remove' : function(){
console.log('remove');
}
}
});
$(document).ready(function(){
$$.document.append(Test, '#test');
var t = setTimeout(function(){
console.log('time out');
$$.document.remove(Test);
}, 1000);
});
})(window);
I've got in my html a div with an id of #test.
Do someone knows how to make them work?
Thanks.
This events are not referring to the moment when the object is added to another one (like window) but they are triggered when you insert another agility object inside the one with binds.
The event remove are working just fine but the event add was replaced by events append and prepend in this commit: https://github.com/arturadib/agility/commit/1b2483333dde3f55b3305f2746e4dd6730a1c364
You can see an example of the remove and append events here:
http://jsbin.com/welcome/14942/edit

Categories