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.
Related
I've been dealing with this problem for some days but I can't find the solution. I have a function in Javascript that generates HTML after an Ajax call is done and I call this function like this:
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
});
And my function is the next:
function reloadInfo(id) {
var div = document.getElementById(id);
...
code += "<img id='led_" + res.id + "' src='green_led.gif' style='cursor: pointer' class='tooltipstered'>";
code += "<img id='" + res.id + "' src='mygraph.jpg'>";
...
div.innerHTML = code;
}
After that, I've tried to use Tooltipster in order to show 'mygraph.jpg' into a tooltip when I put the mouse over the 'green_led.gif' image and hide it when I move out the mouse cursor. To do so, I've used the next code into my $(document).ready():
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
$("body").on('mouseover', '.tooltipstered', function(){
$(this).tooltipster({
trigger: 'custom'
}).tooltipster('open').tooltipster('content', 'MYcontent');
});
});
But it doesn't seem to work. I've read Tooltipster documentation but I don't know what I'm doing wrong when I generate dynamically the HTML code (when I try it with static HTML it works, but I do it a bit different):
JavaScript
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
HTML
<body>
<button id="1" class="tooltipstered" style="float: right">Hover1</button>
<button id="2" class="tooltipstered">Hover1</button>
</body>
The problem is when I generate HTML with JavaScript. First time I put the cursor over the image I don't get any error in the browser console, but the second time I repeat it i get this errors:
Tooltipster: one or more tooltips are already attached to the element
below. Ignoring.
<img id="led_27269" src="green_led.gif" style="cursor: pointer" class="tooltipstered">
Uncaught TypeError: Cannot read property 'width' of undefined
If anybody knows what I'm doing wrong it would be of help. Thank you very much in advanced!!
Two things :
You shall destroy the tooltipsters and recreate them on HTML content change.
Calling a tooltipster method shall be done via $(...).tooltipster(methodName, arg1, arg2,...). Here you should look at the documentation for correct method name and arguments. So, you should call the creation (without method name) each time as you did in $("body").on('mouseover' ....
For recreation :
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
shall be moved :
function reloadInfo(id) {
$(".tooltipstered").tooltipster('destroy');
... your reloading code
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
});
}
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
});
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 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.