How would you override jQuery UI's default functionality so that whenever I set a new title for a dialog - it adds xxx in front of it? So $("#any_dialog_id").dialog("option", "title", "yyy") would set title to xxxyyy.
$().ready(function(){
$("#dialog").dialog();
$(".ui-dialog-title").before("xxx");
// I add the line //
$("#any_dialog_id").dialog("option", "title", "yyy");
});
But he show yyyxxx not xxxyyy
What I have to do, to make it work??
Thanks...
There are many ways you could do this.
The very simplest is to run your line $(".ui-dialog-title").before("xxx"); AFTER each call to opening a dialog. You cannot merely run it once and expect it to re-run on later dialog calls.
Another way to do this is to modify the jquery code. But I HIGHLY disrecommend doing that.
If I were to really want to systematically apply a prefix, I would make a helper function or wrapper that do this for me and call it instead of the jquery dialog directly.
Here is an example of what you might do and I have included a jsfiddle link as well (http://jsfiddle.net/stdw6j5q/1/):
HTML:
<div id="idDiv_MyDialog">Hi 1!</div>
<div id="idDiv_MyDialog2">Hi 2!</div>
<div id="idDiv_MyDialog3">Hi 3!</div>
<div id="idDiv_MyDialog4">Hi 4!</div>
JAVASCRIPT:
jDialog = function(options) {
// THE WRAPPER TAKES TWO EXTRA OPTIONS TO IDENTIFY THE DIALOG AND THE TITLE PREFIX TO USE
// I SET A DEFAULT SELECTOR IF NOTHING IS PASSED IN
var _dialog = options && options.dialog ? options.dialog : '#idDiv_MyDialog';
// HERE YOU CAN SET A DEFAULT PREFIX
var _titlePrefix = options && options.titlePrefix ? options.titlePrefix : 'XYZ: ';
// UPDATE THE TITLE OPTION
options.title = _titlePrefix + options.title;
// PASS THROUGH ALL YOUR NORMAL OPTIONS TO THE DIALOG
$(_dialog).dialog(options);
// THIS RETURNS A HANDLE/REFERENCE TO THE DIALOG CREATED
return $(_dialog);
}
$(function() {
// CALL YOUR WRAPPER WHEN YOU NEED TO CREATE/MOD THE DIALOG
$myDialog1 = jDialog({
title: 'Hey Jude',
close: function(event, ui) { $myDialog2.dialog('open'); }
});
$myDialog2 = jDialog({
dialog: '#idDiv_MyDialog2',
title: 'Don\'t let me down',
autoOpen: false,
close: function(event, ui) { $myDialog3.dialog('open'); }
});
$myDialog3 = jDialog({
dialog: '#idDiv_MyDialog3',
title: 'Take a sad song',
autoOpen: false,
close: function(event, ui) { $myDialog4dialog('open'); }
});
$myDialog4 = jDialog({
dialog: '#idDiv_MyDialog4',
title: 'And make it better',
autoOpen: false
});
});
You can set an event to run whenever a dialog is created that adds the title.
$(document).on('dialogcreate', function(){ // let it bubble up
$(".ui-dialog-title", this).before("xxx"); // add "xxx" before the title of this dialog
});
Related
I have a CKEDITOR plugin that I'm having trouble disabling when there is no selected copy in the editor. Right now, the user can click the button without any highlighted text in the editor. I would like to modify it so that the plugin button is only active when there is copy highlighted in the editor. I've followed the suggestion here, but it isn't working.
Main Plugin Code:
CKEDITOR.plugins.add('cta', {
icons: 'cta',
init: function (editor) {
// Funciton depending on editor selection (taken from the scope) will set the state of our command.
function RefreshState() {
console.log('RefreshState');
var editable = editor.editable(),
// Command that we want to control.
command = editor.getCommand('source'),
range,
commandState;
if (!editable) {
// It might be a case that editable is not yet ready.
console.log("editable not ready yet");
return;
}
// We assume only one range.
range = editable.getDocument().getSelection().getRanges()[0];
console.log(`range: `);
console.log(range);
// The state we're about to set for the command.
commandState = (range && !range.collapsed) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
console.log('commandState');
console.log(commandState);
command.setState(commandState);
}
// We'll use throttled function calls, because this event can be fired very, very frequently.
var throttledFunction = CKEDITOR.tools.eventsBuffer(250, RefreshState);
// Now this is the event that detects all the selection changes.
editor.on('selectionCheck', throttledFunction.input);
// You'll most likely also want to execute this function as soon as editor is ready.
editor.on('instanceReady', function (evt) {
// Also do state refresh on instanceReady.
RefreshState();
});
editor.addCommand('ctabtn', new CKEDITOR.dialogCommand('ctaDialog'));
editor.ui.addButton('cta', {
label: 'Insert Call to Action button',
command: 'ctabtn',
toolbar: 'insert'
});
CKEDITOR.dialog.add('ctaDialog', this.path + 'dialogs/cta.js');
}
});
My dialog code is here:
CKEDITOR.dialog.add('ctaDialog', function (editor) {
return {
// Basic properties of the dialog window: title, minimum size.
title: 'Call to Action',
minWidth: 400,
minHeight: 200,
// Dialog window content definition.
contents: [{
// Definition of the Basic Settings dialog tab (page).
id: 'tab-basic',
label: 'Basic Settings',
// The tab content.
elements: [{
// Text input field for the Call to Action text.
type: 'text',
id: 'cta',
label: 'Call to Action',
// Validation checking whether the field is not empty.
validate: CKEDITOR.dialog.validate.notEmpty("Call to Action field cannot be empty.")
},
{
// Text input field for the link text.
type: 'text',
id: 'url',
label: 'URL',
// Validation checking whether the field is not empty.
validate: CKEDITOR.dialog.validate.notEmpty("URL field cannot be empty.")
}
]
}],
// method invoked when the dialog button is clicked
onShow: function () {
var element = editor.getSelection();
var link = CKEDITOR.plugins.link;
var _this = this.getParentEditor();
var CTAhref = link.getSelectedLink(_this);
this.setValueOf('tab-basic', 'cta', element.getSelectedText().toString());
if (CTAhref != '' && CTAhref !== null) {
this.setValueOf('tab-basic', 'url', CTAhref.$.href);
}
},
// This method is invoked once a user clicks the OK button, confirming the dialog.
onOk: function () {
var dialog = this;
var CTA = editor.document.createElement('a');
CTA.setAttribute('href', dialog.getValueOf('tab-basic', 'url'));
CTA.setAttribute('class', 'btn btn-special--lg');
CTA.setText(dialog.getValueOf('tab-basic', 'cta'));
editor.insertElement(CTA);
}
};
});
Any ideas on why the plugin icon button on the toolbar doesn't become inactive when there is no copy highlighted in the editor? I can see in the console that CKEDITOR.dom.range.collapsed is toggling between TRUE/FALSE depending upon whether text is highlighted or not. It's just not disabling the button.
As stated, the suggested way of handling this was not working for me. What was working was using range.collapsed in returning a true value if a selection was made in the editor. With that, I turned to using Jquery to handle the rest.
// Hacky. But it gets the job done.
// a.cke_button.cke_button__cta.cke_button_off is the selector for my toolbar button.
// The onclick function listed was pulled from looking at the CKeditor functions
// to initiate my plugins modal.
// The setting of the "onclick" prop to null is needed to override the modal onclick
// binding when there is no selection.
range = editable.getDocument().getSelection().getRanges()[0];
if (range.collapsed === false) {
$('a.cke_button.cke_button__cta.cke_button_off').attr("onclick", 'CKEDITOR.tools.callFunction(83,this);return false;');
$('a.cke_button__cta').toggleClass('cta_button_disabled');
} else {
$('a.cke_button.cke_button__cta.cke_button_off').prop("onclick", null);
}
I am trying to build a generic function that I can invoke from anywhere in the application by passing custom parameters to the jQuery UI confirmation dialog. I have been searching and trying different things but the following is the logic I would like to use. What am I doing wrong? Any help is much appreciated.
Here is the function:
function popDialog(h, w, deny_btn, confirm_btn, confirm_title, confirm_message, deny_action, confirm_action) {
var newDialog = $('<div id="dialog-confirm">\
<p>\
<span class="ui-icon ui-icon-alert" style="float: left;margin: 0 7px 60px 0;"></span>\
' + confirm_message + '\
</p>\
</div>');
newDialog.dialog({
resizable: false,
height: h,
width: w,
modal: true,
autoOpen:false,
title: confirm_title,
buttons: [
{text: deny_btn: click: function() {deny_action}},
{text: confirm_btn: click: function() {confirm_action}}
]
});
}
Here is the call:
$("#cancel").click(function(e) {
popDialog("210", // height
"350", // width
"No", // deny_btn
"Yes", // confirm_btn
"Confirm Cancel", // confirm_title
"Are you sure you would like to cancel? Changes will not be saved.", // confirm_message
$('#dialog-confirm').dialog('close'), // deny_action
window.location = '/some/location/index/<?= $class->getClassid() ?>'); //confirm_action
});
So there are a number of issues with this, and I think the best way to tackle them all would be a small refactor. I put the code into jsfiddle for testing and tinkering, and here's what came out:
http://jsfiddle.net/BDh2z/1/
Code is reproduced below:
function popDialog(opts) {
var newDialog = $('<div id="dialog-confirm"><p>'+opts.message+'</p></div>');
if (!$('#dialog-confirm').length){ $('body').append(newDialog); }
newDialog.dialog({
resizable: false,
modal: true,
title: opts.title,
height: opts.height,
width: opts.width,
buttons: opts.buttons
});
};
So above is the new function definition. Things simplified a good amount. Let's go over the changes:
function accepts a options object rather than a bunch of args for clarity
modal html is more simple and clear
autoOpen: false removed, as this prevents the modal from opening without an open() call
button syntax was completely borked in your example, fixed that up and delegated the buttons object to the call, their syntax is quite clean anyway.
actually adds the modal to the html, but only adds it once
Now here's the call:
popDialog({
width: 300,
height: 150,
title: 'testing modal',
message: 'look it worked!',
buttons: {
cancel: function(){ $(this).dialog('close') },
confirm: function(){ $(this).dialog('close') }
}
});
Much cleaner here and easier to understand, mostly because of the fact that we now accept an object rather than a bunch of args. The only issue I found was a weird fluke where jquery UI seems to be collapsing the content section, so I dropped an ugly fix for that in the css of the jsfiddle. This seems to be an issue with jquery UI, but I'll continue to look into it.
This is totally functional in the jsfiddle and looking nice, let me know if there's anything confusing here or if this doesn't exactly solve your issue : )
I think the problem is that you are passing the return value of:
$('#dialog-confirm').dialog('close')
and
window.location = '/some/location/index/<?= $class->getClassid() ?>'
to your popDialog function. You want to do this instead:
Function:
buttons: [
{text: deny_btn, click: deny_action},
{text: confirm_btn, click: confirm_action}
]
Call:
$("#cancel").click(function(e) {
popDialog("210", // height
"350", // width
"No", // deny_btn
"Yes", // confirm_btn
"Confirm Cancel", // confirm_title
"Are you sure you would like to cancel? Changes will not be saved.", // confirm_message
function() { $('#dialog-confirm').dialog('close') }, // deny_action
function() { window.location = '/some/location/index/<?= $class->getClassid() ?>') }; //confirm_action
});
That way you are passing functions to popDialog, and not values.
Just to explain the multi-line problem (can't with comments, but can with answers):
var bad = 'Invalid
syntax';
--
var good = 'Valid' +
'syntax';
I'm opening a dialog using a .load function and then I want to grab the values from the fields in the dialog defining the variables outside the dialog function, but it returns undefined, so my question is, how do I define the variables outside the dialog function to use it inside it,
An example what I want to do.
First I request the dialog:
$( '#dialog-form' ).load('table_models/add_to_table.php',function(){
$( '#dialog-form' ).dialog('open');
});
Now I define the variables and the dialog popup:
$(function() {
var sku = $( "#sku" ),
fba_sku = $( "#fba_sku" ),
asin = $( "#asin" ),
$( "#dialog-form" ).dialog({
title: 'New Product',
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true,
buttons: {
"Done": function() {
// I want to get the var sku, fba_sku, asin here
}
},
}
}
I hope you understand what I want to do, if not I will try to explain it better,
Thanks
EDIT
The .load function being requested from a button on page, then the dialog function is on external JS file, there I want to define first the var of the fields from the dialog form and reuse it for all functions on this page.
Try defining the function outside the object, like so:
var cb = function() { /* stuff with sku, fba_sku, asin */ };
$("#dialog-form").dialog({
...
buttons:{"Done":cb}
});
Your understanding of "'Now' I define [...]" may be flawed–it's unclear where the ready function is defined. .load is asynchronous and will complete at an arbitrary time in the future.
Get the element values in the "Done" function so they're filled with the most recent values.
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.
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.