$(this).dialog is not a function - javascript

...or Why $(this).dialog() fails in Firefox when using dynamic HTML?
I have a a click event that opens a jQuery modal dialog box on a web page, and it is working fine in Chrome and IE, but not in Firefox.
Here is the pertinent code:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
dialogDiv.load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
In Firefox 11, $(this).dialog({ autoOpen: false }) fails with the following error message:
$(this).dialog is not a function
But in IE 9 an Chrome 17 everything is working fine. Any clue why that is?
UPDATE:
Here is my document.ready function where the code above was. I removed it to simplify things. ALERT A is occuring before ALERT B. ALERT A says [object Object]. ALERT B occurs when I click on a link and it says 'undefined'.
$(function () {
alert($.ui); // ALERT A
// Wire up the click event of any dialog links
$('.dialogLink').live('click', function () {
alert($.ui); // ALERT B
return false;
});
});
UPDATE 2:
Now that I pin pointed where the problem was coming from I rephrased my question and posted the minimal code to reproduce the original problem here: Why is FF on OS X losing jQuery-UI in click event handler?

You've got a bit of a syntax/chaining issue if I'm not mistaken:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
//var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
//dialogDiv equals the attribute 'id'
//try and console.log(dialogDiv) right here. what I think you want is:
var dialogDiv = $("<div />");
dialogDiv.attr("id", dialogId).load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
I also don't think this is the correct way to initialize what you're trying to do... can you describe what's going on, on your page?
you may think about doing something like this:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000);
//Build some HTML here in the dialog div, or in a string.
theHTML = $('#'+dialogId).html() || "<p>This is a string of HTML</p>";
$('body').on('click', ".button" function () {
console.log($.ui);
$.dialog({autoOpen:true, html: theHTML})
});

The problem was with a Firefox Add-On. I started Firefox in safe mode, and now everything is working fine. I tried to identify which Add-On caused the problem, and I restarted Firefox with various Add-Ons turned on or off, but I can't seem to be able to reproduce the problem now.

Related

Cannot Pass event When Using JQuery Click()

I can't get data from event.data when using the click function below. If I put "event" in the click(smedata, function(event){}) it doesn't fire. If I remove event it does fire. I've done this hundred times in the past but for whatever reason it doesn't work this time. All I can think is that this code is generated during a callback from closing a dialogue window and that is some how interfering. Appreciate any help.
//This is a callback function in a library that gets called after a dialogue
//window from SharePoint SP.UI.Dialogue gets closed.
OESme.prototype.CloseCallback = function(result, target){
console.log("callback");
try{
var targetArray = target.split(";#");
}
catch(e){
}
//object to be passed to click event
var smedata = {
smejson: target,
id: targetArray[0],
title: targetArray[1],
rank: targetArray[2],
firstname: targetArray[3],
lastname: targetArray[4]
}
var smeID = "smedata" + smedata.id;
var smeIDJQ = "#" + "smedata" + smedata.id;
$("#SMEAddedBox").append(
'<div class="smeitem">' +
'<span id="' + smeID + '">x</span>' + smedata.title +
'</div>'
);
//*******************
//When clicking the x it is suppose to remove itself
//If event is a parameter in the function, it won't fire, if event is removed it fires, but I can't use the object I am trying to pass
//********************
$(smeIDJQ).click(smedata, function(event){
console.log(event.data);
$(this).parent().remove();
});
}
It doesn't look like you're referencing $(smeIDJQ) properly. Also, use .on instead. Like $('#smeIDJQ').on('click', function(){};
All my code was correct. The problem has to do with SharePoint SP.UI.Dialogue.js. All the javascript and jQuery was correct but it was running in the Dialogue window. Basically there are two separate pages running on one page. When the dialogue window closes after the callback the Console in Internet Explorer 11 breaks and doesn't realize that it is suppose to focus on the parent page instead of the child. So it doesn't receive console logs like it should. Closing the Developer tools and reopening (F12) allows the window to refocus the parent properly.

Javascript confirmation cancel button issue [duplicate]

In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!

Change is not displayed on page refresh while using IE8

I have written some JavaScript functions that will do 2 things when a button is clicked:
It will change the label of the button to "Deactivate" from "Activate" and vice versa.
The value of the ActiveStatus property will change to 0 from 1 and vice versa.
The code works alright and the change is displayed perfectly in Mozilla Firefox, but whenever I try display the page in IE 8, change is not displayed, although in database, the value changes perfectly.
Here are the JavaScript codes for the button click:
$(function () {
var stat = document.getElementById("stat").value;
//alert(stat);
if (stat == 1)
document.getElementById("butt").value = "Activate";
else
document.getElementById("butt").value = "Deactivate";
});
function activeStatus(ActiveStatus) {
//alert(ActiveStatus);
if (ActiveStatus == 1) {
return "Activate";
}
else
return "Deactivate";
}
function change() {
var butt = document.getElementById("butt").value;
if (butt == 'Deactivate') {
document.getElementById("butt").value = "Activate";
document.getElementById("stat").value = 1;
}
else {
document.getElementById("butt").value = "Deactivate";
document.getElementById("stat").value = 0;
}
}
Also, an exception message I'm getting whenever I'm trying to view the page in IE 8 is:
Microsoft JScript runtime error: Object doesn't support this property or method
I'm getting this error at the Country.js JavaScript file. The place where I'm getting this exception is:
var url = "/Country/GetAllCountry";
var refresh = function () {
$.getJSON(url, {}, function (data) {
self.Countries(data);
});
};
More specifically, in this line:
self.Countries(data);
None of these happen, when I try to run my application in Firefox. All these happen when I try to run my application in IE 8.
Why am I facing this problem????
EDIT-1: I solved my problem partially. The exception:
Microsoft JScript runtime error: Object doesn't support this property or method
was displayed only because 'Countries' was undefined in Country.js. Countries must be a valid observable, but it has to be declared. I simply had to add this line of code next to it, doing the declaration:
self.Countries = ko.observableArray([]);
Now the exception has disappeared, still the page is not refreshed after the button click.
The answer to this problem is in these 5 simple steps:
Select Tools >> Internet Options.
Click the Settings button in Browsing History.
Select the Every time I visit the webpage radio button.
Click OK to close the Settings dialog.
Click OK to close the Internet Options dialog.
It works perfectly now.
Courtesy: Gonzalo (https://stackoverflow.com/users/203766/gonzalo)

document.activeElement returning a XULElement

I'm trying to get the focused element when the user press CTRL + SPACE on my Firefox add-on.
To do it, I thought to use the document.activeElement to get the focused element, but it is not working. It's always returning a XULElement.
I have just two files in this add-on:
Lib/main.js
var self = require ("sdk/self");
var workers = require("sdk/content/worker");
let worker = workers.Worker({
window: require("sdk/window/utils").getMostRecentBrowserWindow(),
contentScriptFile: self.data.url("script.js")
});
var { Hotkey } = require("sdk/hotkeys");
var showHotKey = Hotkey({
combo: "control-space",
onPress: function() {
worker.port.emit ("getFocused", "");
}
});
and the file Data/script.js
self.port.on ('getFocused', function (msg){
var campo = document.activeElement;
alert (campo);
});
(How you can see here: Add-on SDK Builder Test Project )
So, can someone help me with it?
It's possible to get the input text or textarea from the XULElement and change its text?
Thank you very much!
------------------------ EDIT ----------------------
I don't know if it helps, but, when the url text area (where we write the adress of the sites) has the focus, it returns a
[object HTMLInputElement]
getMostRecentBrowserWindow returns a ChromeWindow object. So it's normal that the activeElement` is a XUL element.
What you should do is
window: require("sdk/window/utils").getMostRecentBrowserWindow().gBrowser.contentWindow

Jquery script not working with IE

I written this script, to add JavaScript functionality to my online shop, the script works fine with Firefox and Chrome, but will not run on ie, and i am not sure why?
i am using jQuery(function( $ ){ instead of .ready due to script conflicts, i have tested the script using .ready and it still does not work with ie.
if anyone has an ideas they would be much appreciated.
jQuery(function( $ ){
setInterval(function(){ updatecart(); },8000);
$('.addtobag').on('click', function(){
event.preventDefault();
var postdata = new Object();
var action = $(this).closest('form').attr('action');
$(':input',$(this).closest('form')).each(function(evt){
var L = $(this).attr('name')
postdata[L] = $(this).val();
});
$.post(action, postdata);
generate('success'); //display banner
updatecart(); //update cart
});
var postdata = new Object();
postdata['basket'] = phpbasket;
function updatecart() {
$.post("/get_cart_details.php", postdata, function (data) {
var obj = $.parseJSON(data);
$('#qty_js').text(obj.items_qty);
$('#amt_js').text(obj.items_value);
});
}
function generate(type) {
var n = noty({
text: 'The item(s) have been added to your basket.',
type: type,
dismissQueue: true,
layout: 'topCenter',
theme: 'defaultTheme'
});
console.log('html: '+n.options.id);
setTimeout(function() {
$.noty.closeAll();
}, 5000);
}
});
Get rid of the console.log() statement. IE < 9 chokes on it and 9 only works if the console is open.
Try adding an event parameter in your click callback
$('.addtobag').on('click', function(event){
A couple things that might be tolerated in some browsers and not IE are that line 12 is missing a semicolon at the end, and the variable phpbasket is not defined (although if you defined it outside of the closure with 'var phpbasket' then you should be ok. If you debug it in IE 9 or higher, you should be able to see line numbers of errors in the console.
Not a complete answer, but it may point you in the right direction. I was actually about to ask a similar question - I found how to get IE 11 to load the jquery, but it required the user to hit "f12" and then "run activex" because apparently IE considered my code potentially unsafe. But when the user tells the activex to run, it works fine.
I am trying to learn how to use jquery to make touchscreen-friendly dropdown menus, so my code was basic - no css, no doctype, just basic html and js. If anyone else could shed some light on this it would be great.

Categories

Resources