Combining multiple jQuery dialog selectors - javascript

I would like to know how to combine the functions of different selectors. All the functions open and close dialogs, but different dialogs. So I don't know if it's possible. It just looks wrong and if someone saw it they would call me an idiot. Right now I have:
$(document).ready(function() {
$('div#basic_dialog').dialog({
autoOpen: false,
buttons: {
"Close": function () {
$('div#basic_dialog').dialog("close");
window.location.href = "#contact";
}
}
})
$('#basic_dialog_button').click(function(){ $('div#basic_dialog').dialog('open'); });
$('div#caption_dialog').dialog({
autoOpen: false,
buttons: {
"Close": function () {
$('div#caption_dialog').dialog("close");
window.location.href = "#contact";
}
}
})
$('#caption_dialog_button').click(function(){ $('div#caption_dialog').dialog('open'); });
$('div#plus_dialog').dialog({
autoOpen: false,
buttons: {
"Close": function () {
$('div#plus_dialog').dialog("close");
window.location.href = "#contact";
}
}
})
$('#plus_dialog_button').click(function(){ $('div#plus_dialog').dialog('open'); });
$('div#skills_dialog').dialog({
autoOpen: false,
buttons: {
"Close": function () {
$('div#skills_dialog').dialog("close");
window.location.href = "#contact";
}
}
})
$('#skills_dialog_button').click(function(){ $('div#skills_dialog').dialog('open'); });
})
But I'm pretty sure that can be prettified somehow. They all open and close different boxes, so I don't know. I know how to do it if they were all doing the exact same function, but mapping that change is beyond me right now.

You can use multiple selectors at one time by separating them by commas.
$('div#basic_dialog, div#caption_dialog, etc...')
However, for cases like yours, I think I would recommend using a class instead.

You can specify any number of selectors to combine into a single result.
You can use like this:
$(document).ready(function() {
$('div#basic_dialog,div#caption_dialog,div#plus_dialog,div#skills_dialog').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$('div#basic_dialog').dialog("close");
window.location.href = "#contact";
}
}
})
$('#basic_dialog_button,#caption_dialog_button,#plus_dialog_button,#skills_dialog_button').click(function() {
$('div#basic_dialog').dialog('open');
});
})
Edited
Give each clickable elements common class and can Use as below:
$('.dialog_button').click(function() {
$(this).dialog('open');
});

Revisiting old questions and after doing this forever now, what would do now:
$(function(){
var close = function(){
$(this).dialog("close");
window.location.href = "#contact";});
$(".dialog").dialog({
autoOpen: false,
buttons: {
"Close": close
}});
$(".dialog-button").click(function(){
var db = $(this).attr("data-val");
$("#"+db).dialog('open');});
});
Then I just add the class .dialog to all the dialog elements and a unique id. For the button handler, I add the ID of the dialog it controls as a data-attribute. The benefit of this way is that I can even set these as vars and then run the functions after I dynamically create more dialogs (if needed) and it will continue to add the dialog functionality to elements not created in the DOM yet, plus I can use another js function that will append the ID of the button handlers as the data-attributes if I need to do that as well.
Works like a charm for me and it's as clean as I can get at this point. Still looking for anyone who can improve on this.

Related

Unable to catch CKEditor change event

I looked through many threads at SO, but could not find an answer that solves my problem. So, I define a CKEditor instance like so:
var editor = $('#test-editor');
editor.ckeditor(function() {}, {
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
However I do not know how can I catch change event. This is what I tried:
var t = editor.ckeditor(function() {
this.on('change', function () {
console.log("test 1");
});
}, {
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
editor.on('change', function() {
console.log("test 2");
});
t.on('change', function() {
console.log("test 3");
});
All these three attempts ended in failure. I should add, that I do not want to loop through all editors on a page, I just want to address one particular editor rendered at component with #test-editor. How can I do that?
The jQuery ckeditor() method returns a jQuery object, which exposes only 5 events of CKEditor in its event handling. In order to use other events, you need to use the CKEditor.editor object by accessing the editor property of the jQuery object.
So, you need to use something like this:
var myeditor = $('#test-editor').ckeditor({
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
myeditor.editor.on('change', function(evt) {
console.log('change detected');
});

jQuery UI Dialog with Confirmation

I have a jQuery UI dialog that gets a line of text. If this text is not contained in a localStorage dictionary, I insert it into the dictionary. If it is present, I want to give the user the option not to overwrite the existing entry in the "ok" handler.
Because jQuery UI dialogs are stateful and persist across multiple calls unless explicitly removed (AFAICT), I'm not seeing a clear path to presenting the "are you sure you want to nuke your previous entry?" alert without resorting to ... uh ... alert.
The question, succinctly stated: Can you create a confirmation box from inside a jQuery UI Dialog?
Thanks.
I have not used jQuery UI Dialog, but you can always create your own html elements and do whatever you wish with them, including layering them on top of the jQuery dialog.
I guess you could have googled something to find these links:
Anyways have it and make fun:
JQuery Dialogs
Jquery Confirmation
Cheers!!!
Ok, it turned out the best way I found to handle this was using closures. Like this (pseudo-code):
getThingieName: handler(function() {
var $dialog;
$dialog = $('<div id="thingie-name-dialog" class="ui-widget"></div>').html("<p>Enter a name for this thingie</p>\n<input type=\"text\" id=\"dlg-thingie-name\" style=\"width: 80%\" />").dialog({
autoOpen: false
}, {
title: 'enter a name',
modal: true,
buttons: {
Add: function() {
var value = $('#dlg-thingie-name').val();
$(this).dialog('close');
$('#thingie-name-dialog').remove();
return handler(value); // <= closure to handle the onAdd
},
Cancel: function() {
$(this).dialog('close');
return $('#thingie-name-dialog').remove();
}
}
});
return $dialog.dialog('open');
}),
getConfirmation: function(message, handler) {
var $dialog;
$dialog = $('<div id="confirmation-dialog" class="ui-widget"></div>').html("<p>" + message + "</p>").dialog({
autoOpen: false
}, {
title: 'confirm overwrite',
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
$('#confirmatio-dialog').remove();
return handler(true); // <= closure to handle onOk
},
Cancel: function() {
$(this).dialog('close');
$('#Thingie-name-dialog').remove();
return handler(false); // <= closure to handle onCancel
}
}
});
return $dialog.dialog('open');
}
// Calling sequence
Snippets.getSnippetName(function(value) {
if (value == null) return false;
if (localStorage.getItem(value)) {
getConfirmation("This thingie, " + value + ", already exists. Overwrite?", function(response) {
if (response) return localStorage.setItem(value, snippet);
});
} else {
localStorage.setItem(value, snippet);
}
}
This may not be the optimal code, but it does make the triggering of the dialogs dependent on the button push by embedding them in the handlers.

jquery ui dynamic dialog

I am fairly new to js and jquery. I basically want to be able to change the table and id variables from an onClick event or something appended to the <a> this way I can modify the variables with php later on. This is just proof of concept, and doesnt seem to be working since I made modifications. Is there a way that I can pass variables from the a to the function?
OVERALL GOAL: I want to have an inline onclick that will pass id and table names from loadMe to the function and display table_render.php?id=someid&table=sometable in the dialog box.
<script>
$(function loadMe(table, id) {
$( "#dialog-view" ).dialog({
autoOpen: false,
height: 600,
width: 700,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$( "#create-view" ).click(function() {
$( "#dialog-view" ).load("table_render.php?id=" + id + "&table=" + table + "").dialog("open");
});
});
</script>
Some text
<div id="dialog-view" title="">
</div>
You are hooking up the event twice, once via onclick and once via jQuery. You need to pick one.
If you pick the jQuery way (recommended) you're going to get the jQuery arguments (which is just one arg, event). However, jQuery will set this to the element that triggered the event (in this case, your A tag). You can use that to get data off of the A tag.
For instance, if you wanted the ID of the A that got clicked, you could do this in your handler:
var clickedId = $(this).attr('id');
If you want to store some arbitrary info (eg. "tableName") for each A tag, you can either use the HTML 5 data attributes (preferable), or just make up your own attributes (which will work, but is "bad form"). For instance:
<a tableName='testimonials'>
var clickedFoo = $(this).attr('tableName');
or (a little better):
<a data-tableName='5'>
var clickedTableName = $(this).attr('data-tableName');
// Also, I believe this would work:
var clickedTableName = $(this).data('tableName');
* EDIT *
Just to try and clarify a little further, the basic overall idea is this:
1) You write out your A tags to the page, via PHP
1A) As you write them out, you put whatever data is specific to them on the A tag, in the form of an attribute or attributes (eg. id='foo' data-bar='baz').
2) You also write out some Javascript code that says "hey, whenever an A tag gets clicked, run this function"
3) Inside the function that you hooked up to the A tag's click event, you use the this variable (which points to the A tag itself) to get the data (the "variables") that you need
3A) For instance, you could use the JQuery "attr" method: $(this).attr('id')
4) Profit! (or at least do something useful with the data you just got)
so i got it working... heres the solution
function createViewer(id, table) {
var id;
var table;
$("#dialog-view").dialog({
autoOpen: false,
width:650,
minHeight:400,
show:{effect: "fade", duration: 500},
hide:"clip",
resizable: false,
modal: true,
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#dialog-view").load("table_render.php?id=" + id + "&table=" + table + "").dialog("open");
};
And the inline code
View Quote
you might want to put $(document).ready()around you functions initialising the dialog and binding the onclick event. Then open the dialog inside the callback of your ajax request.
That way you could dismiss the onclick attribute with the loadFunction, I guess. (tired)
something like:
HTML:
<a href="#" id="trigger" data-my-id="123" data-my-table="myTable">
trigger
</a>
<div id="dialog">
Dialog Contents....
</div>
JS:
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
height: 600,
width: 700,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog("close");
}
}
});
$("#trigger").click(function() {
var id = parseInt( $(this).attr('data-my-id');
var table = $(this).attr('data-my-table');
$("#dialog").load("table_render.php?id=" + id + "&table=" + table + "",
function(){
$("#dialog").dialog("open");
});
});
});​
should do the trick.

Confirmation with save and discard button

How can we create a confirmation alert in javascript with a save and discard button in it?
If we use the code
confirm('Do you want to save it?');
We will get an alert box with ok cancel.
How can we make the text of ok button as save and the other as discard?
You cannot modify the default javascript method "confirm". But, you can override it, for example, with jQuery UI dialog:
window.confirm = function (message) {
var html = "<div style='margin:20px;'><img style='float:left;margin-right:20px;' src='/img/confirm.gif' alt='Confirm'/><div style='display:table;height:1%;'>" + message + "</div></div>";
$(html).dialog({ closeOnEscape: false,
open: function (event, ui) { $('.ui-dialog-titlebar-close').hide(); },
modal: true,
resizable: false,
width: 400,
title: "Confirmation",
buttons: {
"Save": function () {
//Do what you need
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
}
this is not possible
more answers
Connect some of the tons JS framework. For example jQuery+UI
Overwrite window.confirm method, by makin it as wrapper to your favorite JS UI framework.
PROFIT!!!

How do I assign a real function into a javascript object to use as a callback?

I've got a Javascript mess that looks something like:
Note: Not working code, just trying to illustrate my problem...
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: function() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
});
}
}
}
} );
});
I'd like to replace some of the function(){...}s with real functions, to clean things up a bit and to get rid of all that indenting. How do I assign a real function to one of the callbacks rather than an anonymous function?
function abc(){
return false;
}
var callback = {click : abc}
You can then use callback.click.call or callback.click.apply
Give the function name instead of function(){ ... }.
+1 because of the awesome indentation example.
You can define named functions as Joyce stated; you can also considerably clean up that deeply nested code by just declaring some variables (function or not) and spreading the code into multiple, non-nested statements.
The dialog creation would be my first candidate for that type of refactoring (and it demonstrates uses a named function):
function CreateDialog() { //Build dialog box to add stuff to grid
$('<div></div>')
.html('...')
.dialog({
buttons: {
done: { //Finished button on dialog box
OnClick: function() {
$(this).dialog('close');
}
}
}
$(function() {
$(foo).Something( { //Something is a grid control
buttons: {
add: {
onClick: CreateDialog
}
}
}
} );
});
I should also note that you can initialize most jQuery objects (looks like you are using jQueryUI) after they are created. For example, you don't have to configure the buttons all in one shot: http://jqueryui.com/demos/dialog/#option-buttons
OK then, here goes my answer:
Oops.. You did functionname() (note the extra ()s). :sigh: That's what you get for working on this at 3 AM.

Categories

Resources