jQuery UI dialog - check if exists by instance method - jquery-ui-dialog

I'd like to use instance method for testing if jQuery UI Dialog widget has been initialized or not. Regarding to API, this is possible, but it doesn't work for me:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'instance'
demo: http://jsfiddle.net/mDbV7/
UPDATE:
This was a mistake in the documentation, instance method will be available from version 1.11.0, see this issue.

The latest version of jQuery UI no longer allows you to call UI methods on items that are not initialized yet. I've just been wrapping them in an if statement, like:
if ($("#divToBeDialoged").hasClass('ui-dialog-content')) {
// do whatever
} else {
// it is not initialized yet
}
Edit: changed class name, thanks #dmnc

It is also a good habit to empty and destroy dialogs once you're done using them.
I usually use this code in the close event of each dialog
$("#myDialog").dialog({
// other options
close: function(event, ui) {
$(this).empty().dialog('destroy');
}
}
That'd be my advice, rather than asking every time if a dialog exists in an instance make sure that each dialog cleans up after itself.

You can use:
if($('#id').is(':ui-dialog')) {
}
or
var obj = $('<div>test</div>').dialog();
if (obj.is(':ui-dialog')) {
alert('I\'m a dialog')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

If you are making that dialog from an existing id in your html code, like this example:
$('#main').dialog({});
Notice that dialog() adds the class ui-dialog in a <div> parent element generated for it to work. At the #main element, the classes added by dialog() are: ui-dialog-content and ui-widget-content (in jquery-ui-1.9.2). So, in this case, following the example from #jbabey, you can check the existing dialog doing:
if ($('#main').hasClass('ui-dialog-content')) {
// do whatever
}

if ($('#update').is(':data(dialog)'))
{
//#update has dialog
}
else
{
//#update does't have dialog
}

For jQuery UI - v1.10.3
if($( "#myDialog" ).is(':data(uiDialog)')){//is(':data(dialog)') does not work
//Dialog exist
}

another way is
$('.element').is(':data(dialog)');

$("[aria-describedby="IDNAME"]").remove(); - if you want to remove same dialog, which makes as html code DATA
$("[aria-describedby="IDNAME"]") - element of Dialog with additional ID NAME. You can detect data by
($("[aria-describedby="IDNAME"]").lenght > 0)
or remove all dialog with this ID for prevent duplicate window.

Related

What is the 'angular' way of displaying a tooltip / lightbox?

I've been looking around and have not been quite able to get a clear path to the 'angular' way of accomplishing the following. What I'm trying to achieve is displaying a tooltip with information when hovering over a link within an ng-repeat loop. Based on my research, I understood that this is part of the view, and so I should probably handle this in a directive. So, I created an attribute directive called providertooltip. The html declaration is below:
<table>
<tr id="r1" ng-repeat="doc in providers">
<td>
<a providertooltip href="#{{doc.Id}}" ng-mouseover="mouseOverDoc(doc)" ng-mouseleave="mouseLeave()">{{doc.FirstName}} {{doc.LastName}}</a>
</td>
</tr>
</table
<div id="docViewer" style="display:hidden">
<span>{{currentDoc.FirstName}} {{currentDoc.LastName}}</span>
</div>
In the module, I declare my directive, and declare my mouseOver and mouseLeave functions in the directive scope. I also 'emit' an event since this anchor is a child scope of the controller scope for the page. On the controller function (docTable ) which is passed as a controller to a router, I listen for the event. Partial implementation is seen below:
app.directive("providertooltip", function() {
return {
restrict : 'A',
link: function link(scope, element, attrs) {
//hover handler
scope.mouseOverDoc = function(doc){
scope.currentDoc = doc;
scope.$emit('onCurrentDocChange');
element.attr('title',angular.element('#docViewer').html());
element.tooltipster('show');
//docViewer
};
scope.mouseLeave = function() {
element.tooltipster('hide');
}
}
}});
function docTable(docFactory, $scope, $filter, $routeParams) {
$scope.$on('onCurrentDocChange',function(event){
$scope.currentDoc = event.targetScope.currentDoc;
event.stopPropagation();
});
}
Ok, so here is my question. All of the works as expected; Actually, the tooltip doesn't really work so if someone knows a good tooltip library that easily displays div data, please let me know. But, what I'm really confused about is the binding. I have been able to get the tooltip above to work by setting the title ( default tooltip behavior ), but I can see that the binding has not yet occured the first time I hover of a link. I assume that the onCurrentDocChange is not synchronous, so the binding occurs after the tooltip is displayed. If I hover over another link, I see the previous info because as I mentioned the binding occurs in an asynchronous fashion, i.e., calling scope.$emit('onCurrentDocChange') doesn't mean the the parent scope binds by the time the next line is called which shows the tooltip. I have to imagine that this pattern has to occur often out there. One scope does something which should trigger binding on some other part of the page, not necessarily in the same scope. Can someone validate first that the way I'm sending the data from one scope to the other is a valid? Moreover, how do we wait until something is 'bound' before affecting the view. This would be easier if I let the controller mingle with the view, but that is not correct. So, I need the controller to bind data to the scope, then I need the view to 'display a tooltip' for an element with the data. Comments?
To go the angular way correctly start your directive like:
...
directive('showonhover',function() {
return {
link : function(scope, element, attrs) {
element.parent().bind('mouseenter', function() {
element.show();
});
element.parent().bind('mouseleave', function() {
element.hide();
});
}
...
Or start with http://angular-ui.github.io/ link to go the angular-way UI. Look into the bootstrap-ui module - pure angular bootstrap widgets implemented as directives. You can get a clue how the tooltip binding implemented directly from the source of the module - https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js
Also here is another example - (having jQuery and bootstrap scripts included) - use the ui-utils module Jquery passthrough directive ui-jq'. It allows to bind Jquery plugins ( style of $.fn ) directly as angular directive.
Here is their example for binding twitter bootstrap tooltip.
<a title="Easiest. Binding. Ever!" ui-jq="tooltip">
Hover over me for static Tooltip</a>
<a data-original-title="{{tooltip}}" ui-jq="tooltip">Fill the input for a dynamic Tooltip:</a>
<input type="text" ng-model="tooltip" placeholder="Tooltip Content">
<script>
myModule.value('uiJqConfig', {
// The Tooltip namespace
tooltip: {
// Tooltip options. This object will be used as the defaults
placement: 'right'
}
});
</script>
Also look into the official angular documentation for writing directives examples,
and have a happy coding time with Angular!

Apply Css for elements even after postback-jquery

I have many hrefs(with dynamic Ids) in my asp.net app that have the same CssClass=MyClass.
I want these button to be hidden with a condition.
I used the .ready
$(document).ready(function() {
if(condition)
$('.MyClass').css("display","none");
});
the problem is docuement.ready doesn't execut when there is a poctback.
Postback==>Button visible.normal as i've put the code in .ready.
Is there a way to persist the code:$('.MyClass').css("display","none");
I tried to apply .live() on button load,but it doesn't work.
Any ideas?
Thanks in advance.
You can take a different approach, define the style in CSS, like this:
body.conditionClass .MyClass { display: none; }
Then apply that class to <body> on document.ready, like this:
$(function() {
if(condition)
$('body').addClass('conditionClass');
});
Now new elements with .MyClass, anywhere in the <body> will get the display: none styling.
Use the jQuery livequery plugin: http://brandonaaron.net/code/livequery/docs
live() only binds events. When you have installed the plugin, use:
$('.MyClass')
.livequery(function() {
$(this).css("display","none");
});
This will hide items of class MyClass whenever they are found, even if they are created from a Ajax response. You can even use this code in place of the ready function you are currently using.
In this case, Nick Craver's solution is better, but only if you have to evaluate condition just on page load.

jQuery UI interfering with Show()

I use the following code to collapse/show divs in my content page:
$(document).ready(function() {
// Hookup event handlers and execute HTML DOM-related code
$('#nameHyperLink').click(function() {
var div = $('#nameDiv');
var link = $('#nameHyperLink');
if (div.css('display') == 'none') {
link.text('Hide Data');
div.show('100');
}
else {
link.text('Show Data');
div.hide('100');
}
});
});
When I include the jquery UI script file, this code no longer works. The text for the hyperlink changes, but the div is not actually displayed.
Why is this?
I think what you're seeing here is a result of the removal/change of some code in jQuery UI 1.8. Previously, and still in core, any unrecognized string passed to hide/show defaults to the "normal" speed.
For more details, you can see a similar question here: jQuery 1.4.2 - is $("#foo").hide("normal") broken or am I crazy?

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

Call onresize from ASP.NET content page

I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event.
However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.
Any help would be appreciated.
Place the following in your content page:
<script type="text/javascript">
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToHandle, eventHandler);
} else if(element.addEventListener) {
element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
} else {
element[eventToHandle] = eventHandler;
}
}
attachEventHandler(window, "onresize", function() {
// the code you want to run when the browser is resized
});
</script>
That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such.
I had the same problem and have come across this post :
IE Resize Bug Revisited
The above code works but IE has a problem where the onresize is triggered when the body tag changes shape. This blog gives an alternate method which works well
How about use code like the following in your Content Page (C#)?
Page.ClientScript.RegisterStartupScript(this.GetType(), "resizeMyPage", "window.onresize=function(){ resizeMyPage();}", true);
Thus, you could have a resizeMyPage function defined somewhere in the Javascript and it would be run whenever the browser is resized!

Resources