jQuery ui - datepicker prevent refresh onSelect - jquery-ui

I'm using jQuery ui Datepicker to display a yearly inline calendar full of "special dates" (with colors).
This is to allow users to batch special dates by selecting a range and some other details.
$('#calendar').datepicker({
...
, onSelect: function (selectedDate, inst) {
$('.date_pick').toggleClass('focused');
if ($('.date_pick.end').hasClass('focused')) {
$('.date_pick.end').val('');
}
# inst.preventDefault() ? <- not a function
# inst.stopPropagation() ? <- not a function
# return (false) ? <- calendar refreshes anyway
}
...
});
I'm also using qtip to show the details on each date
My problem is when I click on the calendar, it reloads itself entirely, so I loose my qtips.
I'd prefer not to use live() with qtip because I don't like the behavior.
I'd also prefer that the calendar not refresh each time I click on it (but this does not seem possible anyway) but I would probably no longer be able to highlight my selection anymore.
Do you have a suggestion for my problems ?

I was having a similar problem. I was adding custom buttons to the bottom of the datepicker (using $(id).append), but when I would select a date the datepicker would refresh and destroy them.
This is the date selection function for the datepicker in the jquery-ui library:
_selectDate: function(id, dateStr) {
...
if (onSelect)
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
...
if (inst.inline)
this._updateDatepicker(inst);
...
},
As you can see, the function first calls the onSelect event, and then calls _updateDatepicker (which is what redraws the form) if inst.inline is true.
This is my workaround to prevent the form from refreshing while maintaining the selection functionality:
$("#cal_id").datepicker({
onSelect: function(date, inst){
//This is the important line.
//Setting this to false prevents the redraw.
inst.inline = false;
//The remainder of the function simply preserves the
//highlighting functionality without completely redrawing.
//This removes any existing selection styling.
$(".ui-datepicker-calendar .ui-datepicker-current-day").removeClass("ui-datepicker-current-day").children().removeClass("ui-state-active");
//This finds the selected link and styles it accordingly.
//You can probably change the selectors, depending on your layout.
$(".ui-datepicker-calendar TBODY A").each(function(){
if ($(this).text() == inst.selectedDay) {
$(this).addClass("ui-state-active");
$(this).parent().addClass("ui-datepicker-current-day");
}
});
}
});

setting inst.inline to false inside the onselect won't work.
instead try something like
onSelect: function() {
$(this).data('datepicker').inline = true;
},
onClose: function() {
$(this).data('datepicker').inline = false;
}

I have almost the same problem, like some other people, I have some kind of a solution.... but it's not fair:
$('#calendar').datepicker({
...,
onSelect: function (selectedDate, inst)
{
myFunction(selectedDate, inst);
}
});
function myFunction(selectedDate, inst)
{
$('.date_pick').toggleClass('focused');
if ($('.date_pick.end').hasClass('focused')) {
$('.date_pick.end').val('');
}
inst.preventDefault(); # aa; works too, but writing aa; is going too far xD
}
It is not perfect, but works... I'll try to make it works just fine, till then...
EDIT: Solved adding:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

If you just want to select a single day then you have to specify the Month and the Year in JQuery:
$(".ui-datepicker-calendar TBODY [data-month='"+inst.selectedMonth+"'][data-year='"+inst.selectedYear+"'] A").each(function(){

In the case of having some datepickers on the page Yozomiri example will fail. You should do:
onSelect: function(date, inst){
//This is the important line.
//Setting this to false prevents the redraw.
inst.inline = false;
//The remainder of the function simply preserves the
//highlighting functionality without completely redrawing.
//This removes any existing selection styling.
$(this).find(".ui-datepicker-calendar .ui-datepicker-current-day").removeClass("ui-datepicker-current-day").children().removeClass("ui-state-active");
//This finds the selected link and styles it accordingly.
//You can probably change the selectors, depending on your layout.
$(this).find(".ui-datepicker-calendar TBODY td").each(function(){
if ( $(this).find('a').text() == inst.selectedDay && $(this).data('month') == inst.selectedMonth ) {
$(this).find('a').addClass("ui-state-active");
$(this).addClass("ui-datepicker-current-day");
}
});
}
https://jsfiddle.net/g2bgbdne/3/

Related

Coffeescript input not disabled on page load [duplicate]

$input.disabled = true;
or
$input.disabled = "disabled";
Which is the standard way? And, conversely, how do you enable a disabled input?
jQuery 1.6+
To change the disabled property you should use the .prop() function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
jQuery 1.5 and below
The .prop() function doesn't exist, but .attr() does similar:
Set the disabled attribute.
$("input").attr('disabled','disabled');
To enable again, the proper method is to use .removeAttr()
$("input").removeAttr('disabled');
In any version of jQuery
You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:
// assuming an event handler thus 'this'
this.disabled = true;
The advantage to using the .prop() or .attr() methods is that you can set the property for a bunch of selected items.
Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr(), but it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the documentation:
Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5
Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):
$(document).on('event_name', '#your_id', function() {
$(this).removeAttr('disabled');
});
and
$(document).off('event_name', '#your_id', function() {
$(this).attr('disabled','disabled');
});
// Disable #x
$( "#x" ).prop( "disabled", true );
// Enable #x
$( "#x" ).prop( "disabled", false );
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled".
For e.g.:
//To disable
$('.someElement').attr('disabled', 'disabled');
To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:
//To enable
$('.someElement').removeAttr('disabled');
// OR you can set attr to ""
$('.someElement').attr('disabled', '');
reference: http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html
$("input")[0].disabled = true;
or
$("input")[0].disabled = false;
There are many ways using them you can enable/disable any element :
Approach 1
$("#txtName").attr("disabled", true);
Approach 2
$("#txtName").attr("disabled", "disabled");
If you are using jQuery 1.7 or higher version then use prop(), instead of attr().
$("#txtName").prop("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.
Approach 1
$("#txtName").attr("disabled", false);
Approach 2
$("#txtName").attr("disabled", "");
Approach 3
$("#txtName").removeAttr("disabled");
Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.
Use like this,
$( "#id" ).prop( "disabled", true );
$( "#id" ).prop( "disabled", false );
You can put this somewhere global in your code:
$.prototype.enable = function () {
$.each(this, function (index, el) {
$(el).removeAttr('disabled');
});
}
$.prototype.disable = function () {
$.each(this, function (index, el) {
$(el).attr('disabled', 'disabled');
});
}
And then you can write stuff like:
$(".myInputs").enable();
$("#otherInput").disable();
If you just want to invert the current state (like a toggle button behaviour):
$("input").prop('disabled', ! $("input").prop('disabled') );
this works for me
$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);
Update for 2018:
Now there's no need for jQuery and it's been a while since document.querySelector or document.querySelectorAll (for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById, getElementsByClassName, getElementsByTagName
Disabling one field of "input-checkbox" class
document.querySelector('.input-checkbox').disabled = true;
or multiple elements
document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('form input[type="submit"]').prop("disabled", true);
$(".agree").click(function(){
if($(this).prop("checked") == true){
$('form input[type="submit"]').prop("disabled", false);
}
else if($(this).prop("checked") == false){
$('form input[type="submit"]').prop("disabled", true);
}
});
});
</script>
An alternate way to disable the input field is by using jQuery and css like this:
jQuery("#inputFieldId").css({"pointer-events":"none"})
and to enable the same input the code is as follows:
jQuery("#inputFieldId").css({"pointer-events":""})
Disable:
$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.
Enable:
$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.
Disable true for input type :
In case of a specific input type (Ex. Text type input)
$("input[type=text]").attr('disabled', true);
For all type of input type
$("input").attr('disabled', true);
<html>
<body>
Name: <input type="text" id="myText">
<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>
<script>
function disable() {
document.getElementById("myText").disabled = true;
}
function enable() {
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
I used #gnarf answer and added it as function
$.fn.disabled = function (isDisabled) {
if (isDisabled) {
this.attr('disabled', 'disabled');
} else {
this.removeAttr('disabled');
}
};
Then use like this
$('#myElement').disable(true);
2018, without JQuery (ES6)
Disable all input:
[...document.querySelectorAll('input')].map(e => e.disabled = true);
Disable input with id="my-input"
document.getElementById('my-input').disabled = true;
The question is with JQuery, it's just FYI.
Approach 4 (this is extension of wild coder answer)
txtName.disabled=1 // 0 for enable
<input id="txtName">
In jQuery Mobile:
For disable
$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true);
$('#someTextElement').textinput().textinput('disable');
For enable
$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true);
$('#someTextElement').textinput('enable');

jQuery UI Accordion - does refresh method overwrites initialisation settings?

Currently I am working on a project for which I use the jQuery UI Accordion.
Therefore I initialise the accordion on an element by doing
<div id="accordion"></div>
$('#accordion').accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
After init the accordion I append some data coming from an AJAX request. (depends on user interaction)
In a simplified jsfiddle - which does exact the same thing as the ajax call - you can see how this looks like.
So far it seems to be working quite well but there is one problem I face.
In my initialisation I say that I want all panels to be closed but after calling refresh on the accordion everything of those settings seems to be gone and one panel opens.
Note that I implemented jQuery UI v1.10.2 in my fiddle. Update notes say
The refresh method will now recognize panels that have been added or removed. This brings accordion in line with tabs and other widgets that parse the markup to find changes.
Well it does but why has it to "overwrite" the settings I defined for this accordion?
I also thought about the possibility that it might be wrong to create the accordion on an empty <div> so I tested it with a given entry and added some elements afterwards.
But the jsfiddle shows exactly the same results.
In a recent SO thread I found someone who basically does the same thing as I do but in his jsfiddle he faces the same "issue".
He adds a new panel and the first panel opens after the refresh.
My current solution for this issue is to destroy the accordion and recreate it each time there's new content for it.
But this seems quite rough to me and I thought the refresh method solves the need to destroy the accordion each time new content gets applied.
See the last jsfiddle
$(document).ready(function () {
//variable to show "new" content gets appended correctly
var foo = 1;
$('#clickMe').on('click', function () {
var data = '';
for (var i = 0; i < 3; i++) {
data += '<h3>title' + foo + '</h3><div>content</div>';
foo++;
}
if ($('#accordion').hasClass('ui-accordion')) {
$('#accordion').accordion('destroy');
}
$('#accordion').empty().append(data).accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
});
});
Unfortunately it is not an option for me to change the content of the given 3 entries because the amount of panels varies.
So my questions are the one in the title and if this behaviour is wanted like that or if anybody faces the same problem?
For the explanation of this behaviour, have a look in the refresh() method of the jquery-ui accordion widget, the problem you are facing is at line 10 :
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ((options.active === false && options.collapsible === true) || !this.headers.length) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} if (options.active === false) {
this._activate(0); // <-- YOUR PROBLEM IS HERE
// was active, but active panel is gone
} else if (this.active.length && !$.contains(this.element[0], this.active[0])) {
// all remaining panel are disabled
if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate(Math.max(0, options.active - 1));
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index(this.active);
}
this._destroyIcons();
this._refresh();
}

Keep jQuery tooltip open on click?

I want to use jQuery UI's tooltip feature, however I need it so when you click an element (in my case an image) the tool tip stays open. Can this be done? I couldn't see any options for this.
http://api.jqueryui.com/tooltip/
UPDATE here is my code. I thought the 4th line should work but sadly not:
HTML
<img class="jqToolTip" src="/query.gif" title="Text for tool tip here">
Javascript
$('.jqToolTip').tooltip({
disabled: false
}).click(function(){
$(this).tooltip( "open" );
// alert('click');
}).hover(function(){
// alert('mouse in');
}, function(){
// alert('mouse out');
});
I was trying to solve the same exact problem, and I couldn't find the answer anywhere. I finally came up with a solution that works after 4+ hours of searching and experimenting.
What I did was this:
Stopped propagation right away if the state was clicked
Added a click handler to track the state
//This is a naive solution that only handles one tooltip at a time
//You should really move clicked as a data attribute of the element in question
var clicked;
var tooltips = $('a[title]').on('mouseleave focusout mouseover focusin', function(event) {
if (clicked) {
event.stopImmediatePropagation();
}
}).tooltip().click(function() {
var $this = $(this);
var isOpen = $this.data('tooltip');
var method = isOpen ? 'close' : 'open';
$this.tooltip(method);
//verbosity for clarity sake, yes you could just use !isOpen or clicked = (method === 'open')
if (method === 'open') {
clicked = true;
} else {
clicked = false;
}
$this.data('tooltip', !isOpen);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/redmond/jquery-ui.css" rel="stylesheet" />
Tooltips
Hopefully this will help a future googler.
Thanks in part to this post
http://api.jqueryui.com/tooltip/#method-open
$('img.my-class').click(function() {
$(this).tooltip( "open" );
}

jQuery ButtonSet() Hover State Override

I have been tooling around with this all day and can't figure it out...
I have a list of buttons (utilizing the jQuery UI buttonset() functionality) and I am wanting to keep the ui-active class even after I hover off of a button, but for some reason, jQuery UI functionality keeps removing the class and erases the highlight from the button (this is bad because the user then wouldn't know what button they are on).
Here is the code so far:
function showSection(sectionIndex){
$('.listSection').hide();
$('#listSection' + sectionIndex).show();
$('.listSectionHeader.ui-state-active').each(function(){
$(this).removeClass('ui-state-active');
});
$('#listSectionHeader' + sectionIndex).addClass('ui-state-active');
}
var buttons = $( "#listHeader a" );
$.each(buttons, function(){
$(this).bind('mouseleave.button', function(){
if($(this).hasClass('ui-state-active'))
return;
});
});
Something like this: http://jsfiddle.net/4yamQ/ ? Would require an extra class in the css such as:
ui-state-active,
ui-mycustomclass
{
jquery ui styling...
}

jqueryUI Sortable: handling .disableSelection() on form inputs

example: i have an un-ordered list containing a bunch of form inputs.
after making the ul .sortable(), I call .disableSelection() on the sortable (ul) to prevent text-selection when dragging an li item.
..all fine but I need to re/enable text-selection on the form inputs.. or the form is basically un-editable ..
i found a partial solution # http://forum.jquery.com/topic/jquery-ui-sortable-disableselection-firefox-issue-with-inputs
enableSelection, disableSelection seem still to be un-documented: http://wiki.jqueryui.com/Core
any thoughts?
solved . bit of hack but works! .. any comments how i can do this better?
apply .sortable() and then enable text-selection on input fields :
$("#list").sortable({
stop: function () {
// enable text select on inputs
$("#list").find("input")
.bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
e.stopImmediatePropagation();
});
}
}).disableSelection();
// enable text select on inputs
$("#list").find("input")
.bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
e.stopImmediatePropagation();
});
A little improvement from post of Zack - jQuery Plugin
$.fn.extend({
preventDisableSelection: function(){
return this.each(function(i) {
$(this).bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
e.stopImmediatePropagation();
});
});
}
});
And full solution is:
$("#list").sortable({
stop: function () {
// enable text select on inputs
$("#list").find("input").preventDisableSelection();
}
}).disableSelection();
// enable text select on inputs
$("#list").find("input").preventDisableSelection();
jQuery UI 1.9
$("#list").sortable();
$("#list selector").bind('click.sortable mousedown.sortable',function(e){
e.stopImmediatePropagation();
});
selector = input, table, li....
I had the same problem. Solution is quite simple:
$("#list").sortable().disableSelection();
$("#list").find("input").enableSelect();
The following will disable selection for the entire document, but input and select elements will still be functional...
function disableSelection(o) {
var $o = $(o);
if ($o.find('input,select').length) {
$o.children(':not(input,select)').each(function(x,e) {disableSelection(e);});
} else {
$o.disableSelection();
}
}
disableSelection(document);
But note that .disableSelection has been deprecated by jquery-ui and will someday go away.
EASY! just do:
$( "#sortable_container_id input").click(function() { $(this).focus(); });
and replace "sortable_container_id" with the id of the element that is the container of all "sortable" elements.
Quite old, but here is another way:
$('#my-sortable-component').sortable({
// ...
// Add all non draggable parts by class name or id, like search input texts and google maps for example
cancel: '#my-input-text, div.map',
//...
}).disableSelection();

Resources