Setting dateFormat on jQuery UI datepicker, on a non-empty field - jquery-ui

I need my dateformat to be in dd/mm/yyyy
and therefore need to use this following code:
$(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");
But, when using just this line, I don't get the datepicker popup calendar.
If I use this, i get the popup, but then I lose the pre-set date in the value of the field
$(".date-pick").datepicker();
$(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");
See here - https://jsfiddle.net/kneidels/hkbgzvmt/
What code can I use to (1) have the dd/mm/yyyy format, as well as (2) have the pre-set date value shown?
Thanks.

The intended way is to define the defaultDate and dateFormat when instantiating the datepicker: https://jsfiddle.net/tg7yv149/1/
$(function() {
$(".date-pick").datepicker({
defaultDate: $(this).val(),
dateFormat: "dd/mm/yy"
});
});
Another way that works is to store the value in a variable, instantiate the datepicker, then apply the value again: https://jsfiddle.net/Lyneb7j9/
$(function() {
var myval = $(".date-pick").val();
$(".date-pick").datepicker();
$(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");
$(".date-pick").val(myval);
});

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 Fullcalendar: trigger a "create" event using Capybara

I want to trigger a "create" event in jQuery Fullcalendar using Capybara, but I don't know which element to click. I'm not sure whether this is possible with Capybara anyway...
I've created a demo where if a user clicks on a calendar day a new calendar event is created.
See the dayclick callback code:
dayClick: function(date, allDay, jsEvent, view) {
if (allDay) {
alert('Clicked on the entire day: ' + date);
}else{
alert('Clicked on the slot: ' + date);
}
// change the day's background to highlight the fact that its been clicked
$(this).css('background-color', 'red');
// Create a new event for the day that was clicked
var myEvent = {
title:"my new event",
allDay: true,
start: date,
end: date
};
cal.fullCalendar( 'renderEvent', myEvent );
}
You can then click on a date in jQuery Fullcalendar (which will trigger the creation of a new event when the above code is in place) using Capybara as follows:
page.find(:css, "td[data-date='2013-11-06']").click()
Note that you'll need to tailor the CSS to choose exactly which FullCalendar day (i.e. TD element) to click, but this is just an example.
See the Caybara documentation here for how to do this.

How to correctly bind and initialize a jQuery Mobile range slider with knockout.js?

I have some trouble to get a JQM range slider to work well with knockout.
This is a very basic html code for a JQM slider:
<input type="range" name="quantity-slider" id="quantity-slider" min="0" max="10">
I have created as a sample this knockout binding, applied on document ready:
var ViewModel = function() {
this.quantity = ko.observable(4);
}
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
I read over the internet some posts from other people that also found some problems related to the JQM initialization of the range slider (for example here: http://css.dzone.com/articles/knockoutjs-binding-helper and here: http://www.programico.com/1/post/2012/12/knockoutjs-jquerymobile-slider.html) and provide a working solution, each with his own custom binding implementation.
One of them, is as follows (by http://www.hughanderson.com/):
data-bind="value: quantity, slider: quantity"
So far, so good. After that, i run into this problem:
if the JQM slider is on the first page, it works. When the JQM slider is on a second page, is not working anymore.
I think it is an issue related to this particulary JQM widget and his DOM manipulation, as i can understand. To better explain this, i have made two jsFiddle, where i just only swap the order of two JQM pages:
not working: http://jsfiddle.net/5q38Q/ slider on the second JQM page
working: http://jsfiddle.net/5q38Q/1/ slider on the first JQM page
Can someone explain please, which is the right way to initialize the knockout binding for a JQM slider? Maybe there is another way to write a custom binding for the JQM slider, or the knockout binding shall be put in the pagebeforeshow event?
UPDATE:
With following change, the slider displays the correct value, and is synchronized also with the text-input part:
$(document).on('pagebeforeshow', '#slider-page', function(){
$('#quantity-slider').val(viewModel.quantity());
$('#quantity-slider').slider('refresh');
});
but im wonder if there is no better solution.
At least, together with Varun's custom binding, it works now for me very well!
I ran into the same issue. This is how I solved it. Although this solution does not update the observable when you edit the value directly using the text input. (I don't display the input text box, so this solution is sufficient for me)
http://jsfiddle.net/WMr8D/9/
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.quantity = ko.observable(4);
};
ko.bindingHandlers.slider = {
init: function (element, valueAccessor) {
var value = valueAccessor();
$(document).on({
"mouseup touchend keypress": function (elem) {
value($('#' + element.id).val());
}
}, ".c-slider");
}
};
ko.applyBindings(new ViewModel());
});
after some hours spent to test all variations found on the web about this issue, i ended up with following solution, maybe this helps some other people to spare time:
Final working fiddle: http://jsfiddle.net/CT7fy/
The question was about how to integrate knockout.js and the JQuery Mobile slider with multipage navigation, which, i think, will be one of the most common situation.
So i'm sorry that i cannot consider Varun's answer as complete and satisfiyng, but i must say, without Varun's custom bindinghandler i would have never found a working solution.
Here is the custom binding handler, slighlty modified:
/* custom binding handler thanks to Varun http://stackoverflow.com/a/16493161/2308978 */
ko.bindingHandlers.slider = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = valueAccessor();
$(document).on({
"mouseup touchend keypress": function (elem) {
var sliderVal = $('#' + element.id).val();
value(sliderVal);
}
}, ".ui-slider");
}
};
...and here is the page initialization:
$(document).on('pagebeforeshow', '#slider-page', function(){
$('#quantity-slider').val(viewModel.quantity());
$('#quantity-slider').slider('refresh');
});
The text-part of the slider is also synchronized, after you pres enter or tab, as this is the standard slider behavior.
In the custom handler, it's more reliable to bind to the "change" event than to bind to mouseup touchend and keypress. Also the pagebeforeshow event is not necessary. You can just set the value attribute during init in the handler:
ko.bindingHandlers.slider = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = valueAccessor();
$(element).attr("value", value());
$(document).on({
"change": function (elem) {
var sliderVal = $('#' + element.id).val();
value(sliderVal);
}
}, ".ui-slider");
}
};
See example: http://jsfiddle.net/ZbrB7/2483/

jQuery ui - datepicker prevent refresh onSelect

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/

How can I get the JqueryUI datepicker show "Today" in the input box

When the user selects today in the datepicker, I want the associated input box to show the word "Today".
Is there any reasonable way to accomplish this?
You could attach a .change() handler to the input that checks the selected date when the value is changed, and updates the value with "Today" if necessary.
Try it out: http://jsfiddle.net/gn4Fj/
$('input').datepicker()
.change(function() {
var today = new Date().getDate();
var val = new Date(this.value).getDate();
if(today === val)
this.value = "Today";
});
Are you looking the showButtonPanel: true option?

Resources