Set JavaScript object property with a function - javascript

I'm trying to set the property of an object with a function but instead, I get a value of 100 and the slide bar stuck in the middle. What am I doing wrong? Here is my code:
term: {
min: 1,
max: function(){
var period = document.getElementById("duration").value;
if (this.period == "days"){
var value = 31;
} else if(this.period == "months"){
value = 12;
} else {
value = 365;
};
return value;
},
step: 1,
_value: 10,
get value() {
return parseFloat(this._value);
},
set value(val) {
this._value = val;
},
reset: function() {
this._value = 12;
}
},
And this is the result on th UI:
EDIT:
This is how I use min and max:
document.querySelectorAll('.controller-row')
.forEach(function(group) {
var min = inputValues[group.id].min;
var max = inputValues[group.id].max;
var value = inputValues[group.id].value;
var step = inputValues[group.id].step;
var boundary = max ? 100 * (value - min) / (max - min) : 0;
var range = group.querySelector('input[type=range]');
range.setAttribute('style',
'background-image: linear-gradient(90deg, #4098FF 0%, #4098FF ' + boundary + '%, white ' + boundary + '%);'
);
range.min = min;
range.max = max;
range.value = value;
range.step = step;
var textInput = group.querySelector('input[type=number]');
textInput.min = min;
textInput.max = max;
textInput.value = value;
textInput.step = step;
});

Related

how to implement the "evasion" property in the "kick" method?

I want to implement the logic of the hero's evasion in the "kick" method.For the Hero a certain amount of the "evasion" property is set, on the basis of which its percentage of evasion depends, an example of the "evasion" archer is 0.6 that is 60 percent chance to evade the "kick".How to properly implement this logic and that the result of the message, display damage or evasion
function Unit(maxHealth, basicDamage, evasion, type) {
this.maxHealth = maxHealth;
this.currentHeaalth = maxHealth;
this.basicDamage = basicDamage;
this.evasion = evasion;
this.type = type;
/*method for showing the status of life, true if the "health" is greater
than 0 and false if equal to or lower */
this.isAlive = function () {
return this.currentHeaalth > 0
};
/* a method that
shows the level of health*/
this.getFormattedHealth = function () {
return this.currentHeaalth + '/' + this.maxHealth + ' HP';
};
/*a method that returns the base damage of the heroand damage to the
weapon (if it is set)*/
this.getDamage = function () {
return (this.weapon ? this.weapon.getDamage() : 0) + this.basicDamage;
};
/* The method of hitting
the hero for the chosen purpose*/
this.kick = function (target) {
if (this.isAlive()) {
target.currentHeaalth = Math.max(0, target.currentHeaalth - this.getDamage());
}
return this;
};
/*method for showing all the characteristics of the hero and changes
with them*/
this.toString = function () {
return "Type - " + this.type + ", is alive - " + this.isAlive() + ", " + this.getFormattedHealth() + ', hero current damage - ' + this.getDamage() + ' points' +
", hero evasion - " + this.evasion;
}
}
function Archer(maxHealth, basicDamage, evasion) {
Unit.apply(this, arguments);
this.type = "archer";
}
var archer = new Archer(60, 5, 0.6);
function Swordsman(maxHealth, basicDamage, evasion) {
Unit.apply(this, arguments);
this.type = "swordsman";
}
var swordsman = new Swordsman(100, 10, 0.3)
while (archer.isAlive() && swordsman.isAlive()) {
archer.kick(swordsman);
swordsman.kick(archer);
}
console.log(archer.toString());
console.log(swordsman.toString());
Write a function which fills an array with 10 digit of 0s and 1s according to evasion and return a random 1 or 0:
let evasion = 0.4,
probability = function() {
var notRandomNumbers = [],
maxEvasion = 0;
if ((evasion + '').split('.')[0] == 1 && (evasion + '').split('.')[1] == 0) {
maxEvasion = 10;
} else {
maxEvasion = (evasion + '').split('.')[1];
}
for (var i = 0; i < maxEvasion; i++) {
notRandomNumbers.push(1);
}
for (var i = 0; i < 10 - maxEvasion; i++) {
notRandomNumbers.push(0);
}
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}
console.log('1 )', probability());
console.log('2 )', probability());
console.log('3 )', probability());
console.log('4 )', probability());
Use it in kick function.
this.kick = function(target) {
if (this.isAlive()) {
target.currentHeaalth = Math.max(
0,
target.currentHeaalth - this.probability() * this.getDamage()
);
}
};
Full code will be this:
function Unit(maxHealth, basicDamage, evasion, type) {
this.maxHealth = maxHealth;
this.currentHeaalth = maxHealth;
this.basicDamage = basicDamage;
this.evasion = evasion;
this.type = type;
/*method for showing the status of life, true if the "health" is greater
than 0 and false if equal to or lower */
this.isAlive = function() {
return this.currentHeaalth > 0;
};
/* a method that
shows the level of health*/
this.getFormattedHealth = function() {
return this.currentHeaalth + "/" + this.maxHealth + " HP";
};
this.probability = function() {
var notRandomNumbers = [],
maxEvasion = 0;
if (
(this.evasion + "").split(".")[0] == 1 &&
(this.evasion + "").split(".")[1] == 0
) {
maxEvasion = 10;
} else {
maxEvasion = (this.evasion + "").split(".")[1];
}
for (var i = 0; i < maxEvasion; i++) {
notRandomNumbers.push(1);
}
for (var i = 0; i < 10 - maxEvasion; i++) {
notRandomNumbers.push(0);
}
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
};
/*a method that returns the base damage of the heroand damage to the
weapon (if it is set)*/
this.getDamage = function() {
return (this.weapon ? this.weapon.getDamage() : 0) + this.basicDamage;
};
/* The method of hitting
the hero for the chosen purpose*/
this.kick = function(target) {
if (this.isAlive()) {
target.currentHeaalth = Math.max(
0,
target.currentHeaalth - this.probability() * this.getDamage()
);
}
};
/*method for showing all the characteristics of the hero and changes
with them*/
this.toString = function() {
return (
"Type: " +
this.type +
", is alive: " +
this.isAlive() +
", " +
this.getFormattedHealth() +
", hero current damage: " +
this.getDamage() +
" points" +
", hero evasion - " +
this.evasion
);
};
}
function Archer(maxHealth, basicDamage, evasion) {
Unit.apply(this, arguments);
this.type = "archer";
}
var archer = new Archer(60, 5, 0.6);
function Swordsman(maxHealth, basicDamage, evasion) {
Unit.apply(this, arguments);
this.type = "swordsman";
}
var swordsman = new Swordsman(100, 10, 0.3);
while (archer.isAlive() && swordsman.isAlive()) {
archer.kick(swordsman);
swordsman.kick(archer);
}
console.log(archer.toString());
console.log(swordsman.toString());
Hope this helps you.

Cant call the public method on jquery Plugin

I developed a plugin and when I call the plugin getting an error like Uncaught TypeError: Cannot read property 'convert' of undefined.
Here is my Plugin ,Its not working when I calling in my scripts
( function ($) {
$.siPrifixx = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {
}
}
var plugin = this;
plugin.settings = {
maxDigits: 8,
seperator: true,
decimal: 1,
popUp: false,
countUp:false
}
var $element = $(element),
element = element;
plugin.init = function() {
var value =$(element);
console.log(value);
plugin.settings = $.extend({
}, defaults, options);
var maxDigits = plugin.settings.maxDigits;
console.log(defaults);
if (typeof value === 'string') {
var parts = value.split(",");
var num = parts.join("");
var isNumber = regIsNumber(num)
if(isNumber){
var number = (parseInt(num));
}else{
number = num;
}
}else if (typeof value === 'number'){
number = value
}
var data_max = $(this).attr('data-max-digit');
if(typeof data_max !== 'undefined'){
maxDigits = data_max;
}
var checkNumber = typeof number !== 'undefined' && !isNaN(number) && Math.round(number).toString().length > maxDigits;
if (plugin.settings.popUp && checkNumber) {
$(this).addClass('tooltip', value);
var tootip = $(this).tooltipster({
theme: 'tooltipster-default',
functionInit: function () {
return value
}
})
if(!tootip)
console.log("We couldn't find tooltipster function.Please make sure you have loaded the plugin")
}
if (plugin.settings.countUp && (Math.round(value).toString().length <= maxDigits)) {
var cUp = new countUp(
plugin.settings.countUp, 0, Number(value), 0, 1, null);
cUp.start();
if(!cUp)
console.log("We couldn't find counter function.Please make sure you have loaded the plugin")
}
if (checkNumber) {
var results = plugin.convert(number);
$(this).html(results);
} else {
if (plugin.settings.seperator) {
var cvalue = numberWithCommas(value)
$(this).html(cvalue)
} else {
$(this).html(value)
}
if(typeof value === 'string')
if(checkDate(value)){
$(this).html(value)
}
}
}
plugin.convert = function(number){
var n = settings.decimal
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
console.log(number);
return number;
}
plugin.init();
//use to convert numbers with comma seperated
}
$.fn.siPrifixx = function (options) {
return this.each(function() {
if (undefined == $(this).data('siPrifixx')) {
var plugin = new $.siPrifixx(this,options);
$(this).data('siPrifixx', plugin);
}
});
};
}(jQuery));
I use to call the plugin by $(this).data('siPrifixx').convert(value);});
What is the problem with my code?How can I modify my plugin to gets works?
How can I call convert method in code.
One approach would be to divide plugin into individual portion which each return expected result, then merge the discrete working portions one by one until the full plugin in functional
(function($) {
var settings = {
maxDigits: 8,
seperator: true,
decimal: 0,
popUp: false,
countUp: false
}
function convert(number, options) {
var opts = $.extend(settings, options || {});
var n = opts.decimal;
console.log(opts);
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
this.data("number", number); // set `number` at `.data("number")`
return this; // return `this` for chaining jQuery methods
}
$.fn.convert = convert;
}(jQuery));
var div = $("div");
div.convert(1500000, {decimal:1});
console.log(div.data("number"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
You should call it like this:
$(this).data('siPrifixx').plugin.convert(value);});

Recursion prevents function from being clicked more times in a row

I have created a simple script using recursion, to change the position of images.
It loop throught them and adjust their position , the script is relative easy code :
var img = document.getElementsByClassName("container")[0];
var X = 0;
var Y = 0;
var check;
function all() {
var decko = img.children;
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function() {
pushIt(img.length, img.children, 0, 0)
}
function pushIt(max, target, index, count) {
if (count == max) {
return;
}
var tmp = target[index];
var matrix =window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left=matrix.split(",")[4];
var translate_top=matrix.split(",")[5].split(")")[0]-100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function(){
pushIt(max, target, index + 1, count + 1);
},150)
}
Here you can see how it works. The problem is when there are a lot of images.
When i click which invokes the function , it loops throught all images ( 30 + in my case ). If i click two times in a sec , it will loop throught the all images , and THEN it will execute the function 2 nd time which is in my case unwanted behavior ( looks laggy ). Is there any way to prevent this behavior? I have chosen recursion , bcs it seems like easiest choice for this.
You had a couple if issues with your JavaScript that were throwing some errors, namely max was undefined in your function. I got this working HERE
var img = document.getElementsByClassName("container")[0];
var decko = img.children;
var X = 0;
var Y = 0;
var check;
var running = false;
function all() {
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function () {
if (!running) {
running = true;
pushIt(decko.length, img.children, 0, 0);
}
}
var pushIt = function (max, target, index, count) {
if (count == max) {
running = false;
return;
}
var tmp = target[index];
var matrix = window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left = matrix.split(",")[4];
var translate_top = matrix.split(",")[5].split(")")[0] - 100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function () {
console.log(running);
pushIt(max, target, index + 1, count + 1);
}, 150)
}

jQuery No-Ui-Slider, how to lock multiple interconnected sliders to always sum 100?

I am using NoUiSlider in some pages which could have 3, 4 or 5 sliders (http://refreshless.com/nouislider/).
I need to set the sliders to have a total value which is constrained to 100, so that if I raise the value of a slider, the others should lower a little and vice-versa, but I really don't know how to do it.
Can anyone help me please? Thanks!
jQuery code:
$(".slider.tied").each(function() {
var context = $(this).addClass("noUiSlider");
var input = context.prev(".amount"); // the input containing the actual slider value
var val = input.val();
var min = input.data("min");
var max = input.data("max");
context.noUiSlider({
range: [min, max],
start: val,
step: 1,
handles: 1,
slide: function() {
var value = $(this).val();
input.val(value);
}
});
});
A possible solution:
var init = true;
var elements = $(".multislider").children(".slider.tied").length;
var MAX = 100;
var initValue = (MAX / elements) >> 0;
var InitMod = MAX % elements;
$(".slider.tied").each(function() {
var slidersTied = $(".slider.tied");
var context = $(this);
var input = context.prev(".amount");
var val = input.data('answer');
var min = input.data('min');
var max = input.data('max');
var range = 1;
var proceed = false;
$(this).empty().slider({
value: val,
min: min,
max: max,
range: range,
animate: "slow",
create: function(event, ui){
if (InitMod > 0) {
$(this).slider('value', initValue + 1);
$(this).prev('.amount').val(initValue + 1);
InitMod = InitMod - 1;
}
else
{
$(this).slider('value', initValue);
$(this).prev('.amount').val(initValue);
}
},
slide: function(e, ui) {
// Update display to current value
$(this).prev('.amount').val(ui.value);
var current = ($(this).index() / 2) >> 0;
var total = 0;
var counter = 0
slidersTied.not(this).each(function() {
total += $(this).slider("option", "value");
counter += 1;
});
total += ui.value;
if (total != MAX){
proceed = true;
}
var missing = MAX - total;
console.log("missing: " + missing);
counter = 0;
if(proceed) {
//load elements array
var elements = [];
slidersTied.each(function() {
elements[counter] = $(this);
counter += 1;
});
var endIndex = counter - 1;
counter = endIndex + 1;
while (missing != 0) {
console.log("current counter: " + counter);
do {
if (counter == 0)
{
counter = endIndex;
}
else
{
counter = counter - 1;
}
} while(counter == current)
console.log("elemento attuale: " + counter);
var value = elements[counter].slider("option", "value");
var result = value + missing;
if (result >= 0)
{
elements[counter].slider('value', result);
elements[counter].prev('.amount').val(result);
missing = 0;
}
else
{
missing = result;
elements[counter].slider('value', 0);
elements[counter].prev('.amount').val(0);
}
}
}
}
});
});
Here's a fiddle:
http://jsfiddle.net/vuQz5/11/
Take care of setting the value of MAX variable to desired value (the sum of all slider's value together...

Javascript Date Picker Calendar

I would like to be able to specify a default date in the date box before the user input.
The JavaScript for the calendar is:
/* ********************************************************************
* Calendar Date Selector - v1.1
* Copyright (c) 2011 - GreyWyvern
*
* - Licenced for free distribution under the BSDL
* http://www.opensource.org/licenses/bsd-license.php
*
* The Calendar Date Selector is the simplest date selection calendar
* you will ever use! No need to insert any javascript into your HTML;
* the script will automatically transform <input> elements with
* attribute type="date" (HTML5) into calendar inputs, respecting both
* min and max attributes as well. Your users then just click the input
* to invoke the calendar input. Works in all major browsers.
*
* Customize the CSS, or date format used (see below), or not! This
* script is completely ready to use as-is. Be sure to include the
* calendar.css stylesheet in your HTML document as well.
*
*/
(function calendarSelector() {
var self = this;
/* ******************************************************************
* Select a Date Format
*
* The calendar script uses the same syntax as the PHP date()
* function, however only the code characters listed below are
* supported; mix and match them as you please with the following
* caveat: The format you use MUST include one (and only one) value
* from each of the Day, Month and Year lists or the calendar will
* not function properly.
*
* Supported date format codes (see http://www.php.net/date):
*
* Day: d, j
* Month: m, n, F, M
* Year: Y, y
* Optional: D, l, S, w
*
* For the day name and month name codes, only the English language
* representations are supported.
*
* Regardless of the date format you choose, the HTML5 date input
* element only accepts source code values in the "Y-m-d" format, so
* be sure to write them as such in your form HTML code. This script
* will rewrite the displayed value using the format given below,
* which will also be the format sent to the server on submission.
*
* NOTE: If a user has javascript disabled, the value will default
* to the Y-m-d format, so it's good practice to allow your server
* side script to accept both.
*
* Example formats:
* - "Y-m-d" => 2010-12-31 (script default)
* - "F jS, Y" => December 31st, 2010
* - 'm/j/y" => 12/31/10
* - 'Y-M-j" => 2010-Dec-31
* - "D M j, Y" => Fri Dec 31, 2010
*
*/
this.format = "D j M Y";
this.weekStart = 0; // 0 = Sunday, 1 = Monday
/* ******************************************************************
* Modified PHP date() implementation in Javascript
* by Carlos R. L. Rodrigues and co. - Much thanks!
* - http://phpjs.org/functions/date
*
*/
this.date = function(format, ts) {
var jsd = (typeof ts === 'undefined') ? new Date() : (ts instanceof Date) ? new Date(ts) : new Date(ts * 1000);
var fChr = /\\?([a-z])/gi, fChrCb = function (t, s) { return f[t] ? f[t]() : s; };
var _pad = function (n, c) { return ((n = n + "").length < c) ? new Array((++c) - n.length).join("0") + n : n; };
var txt_words = [
"Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
], txt_ordin = {1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st"};
var f = { // Day
d: function() { return _pad(f.j(), 2); },
D: function() { return f.l().slice(0, 3); },
j: function() { return jsd.getDate(); },
l: function() { return txt_words[f.w()] + 'day'; },
S: function() { return txt_ordin[f.j()] || 'th'; },
w: function() { return jsd.getDay(); },
// Month
F: function() { return txt_words[6 + f.n()]; },
m: function() { return _pad(f.n(), 2); },
M: function() { return f.F().slice(0, 3); },
n: function() { return jsd.getMonth() + 1; },
// Year
Y: function() { return jsd.getFullYear(); },
y: function() { return (f.Y() + "").slice(-2); }
};
return format.replace(fChr, fChrCb);
};
// ***** Parse a date from a string *********************************
this.parse = function(data, rtrn, format) {
if (!data) return rtrn;
if (!format) format = this.format;
var fChr = /\\?([a-z])/gi, fChrCb = function (t, s) { return f[t] ? f[t]() : s; }, ordr = [];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var f = { // Day
d: function() { ordr.push("d"); return "(\\d\\d)"; },
D: function() { return "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)"; },
j: function() { ordr.push("d"); return "(\\d\\d?)"; },
l: function() { return "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day"; },
S: function() { return "(?:st|nd|rd|th)"; },
w: function() { return "\\d"; },
// Month
F: function() { ordr.push("M"); return "(January|February|March|April|May|June|July|August|September|October|November|December)"; },
m: function() { ordr.push("m"); return "(\\d\\d)"; },
M: function() { ordr.push("M"); return "(" + months.join("|") + ")"; },
n: function() { ordr.push("m"); return "(\\d\\d?)"; },
// Year
Y: function() { ordr.push("y"); return "(\\d{4})"; },
y: function() { ordr.push("y"); return "(\\d\\d)"; }
};
format = format.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var outp = data.match(new RegExp("^\\s*" + format.replace(fChr, fChrCb) + "\\s*$", ""));
if (outp && ordr.length == 3) {
for (var x = 0, val = []; x < ordr.length; x++) {
switch (ordr[x]) {
case "d": val[2] = parseInt(outp[x + 1], 10); break;
case "m": val[1] = parseInt(outp[x + 1], 10) - 1; break;
case "y": val[0] = parseInt(outp[x + 1], 10); break;
case "M":
for (var y = 0, o = outp[x + 1].slice(0, 3); y < months.length; y++)
if (o == months[y]) val[1] = y;
}
} return new Date(val[0], val[1], val[2]);
} else return rtrn;
};
// ***** Show the calendar ******************************************
this.show = function(elem) {
if (this.cal.parentNode == document.body && elem != this.elem) this.hide(false);
if (this.cal.parentNode != document.body || elem != this.elem) {
this.elem = elem;
this.point = this.parse(elem.value, new Date());
this.build();
var cleft = ctop = 0, obj = elem;
do { cleft += obj.offsetLeft; ctop += obj.offsetTop; } while (obj = obj.offsetParent);
this.cal.style.left = cleft + "px";
this.cal.style.top = (ctop + elem.offsetHeight) + "px";
document.body.appendChild(this.cal);
setTimeout(function() {
_addListener(document.documentElement, 'click', self.listener = function() {
self.hide(false);
}, false);
}, 0);
} else this.hide(false);
};
// ***** Hide the calendar ******************************************
this.hide = function(value) {
if (typeof value == "string") this.elem.value = value;
this.cal = document.body.removeChild(this.cal);
_removeListener(document.documentElement, 'click', this.listener, false);
};
// ***** Build the body of the calendar *****************************
this.build = function() {
var mindt = (mindt = this.parse(this.elem.getAttribute('min'), false, "Y-m-d")) ? this.date("Ymd", mindt) : "";
var maxdt = (maxdt = this.parse(this.elem.getAttribute('max'), false, "Y-m-d")) ? this.date("Ymd", maxdt) : "";
var slctd = (slctd = this.parse(this.elem.value, false)) ? this.date("Ymd", slctd) : "";
this.point.setDate(15);
if (mindt) while (this.date("Ym", this.point) < mindt.substr(0, 6)) this.point.setMonth(this.point.getMonth() + 1);
if (maxdt) while (this.date("Ym", this.point) > maxdt.substr(0, 6)) this.point.setMonth(this.point.getMonth() - 1);
var day = new Date(this.point.getTime()), today = this.date("Ymd");
day.setDate(1);
day.setDate(1 - day.getDay() + this.weekStart);
while (this.cal.tBody.firstChild) this.cal.tBody.removeChild(this.cal.tBody.firstChild);
do {
var tr = document.createElement('tr');
for (var x = 0, ymd; x < 7; x++) {
ymd = this.date("Ymd", day);
var td = document.createElement('td');
td.className = "";
td.title = this.date("l", day);
td.date = new Date(day.getTime());
if ((!mindt || ymd >= mindt) && (!maxdt || ymd <= maxdt)) {
td.className = "valid";
td.onclick = function() { self.hide(self.date(self.format, this.date)); };
} else td.className = "";
if (ymd == slctd) td.className += " selected";
if (day.getMonth() == this.point.getMonth()) {
td.className += " month";
if (ymd == today) td.className += " today";
if (!day.getDay() || day.getDay() == 6) td.className += " weekend";
} td.appendChild(document.createTextNode(day.getDate()));
tr.appendChild(td);
day.setDate(day.getDate() + 1);
} this.cal.tBody.appendChild(tr);
} while (day.getMonth() == this.point.getMonth());
if (mindt) {
mindt = (this.point.getFullYear() - mindt.substr(0, 4)) * 12 - parseInt(mindt.substr(4, 2), 10) + this.point.getMonth() + 1;
this.cal.tHeads[0].className = (mindt < 1) ? "disabled" : "";
this.cal.tHeads[1].getElementsByTagName('strong')[0].className = (mindt < 1) ? "disabled" : "";
} this.cal.tHeads[1].getElementsByTagName('span')[0].firstChild.nodeValue = this.date("F, Y", point);
if (maxdt) {
maxdt = (this.point.getFullYear() - maxdt.substr(0, 4)) * 12 - parseInt(maxdt.substr(4, 2), 10) + this.point.getMonth() + 1;
this.cal.tHeads[2].className = (maxdt > -1) ? "disabled" : "";
this.cal.tHeads[1].getElementsByTagName('em')[0].className = (maxdt > -1) ? "disabled" : "";
}
};
var _addListener = function(elem, type, listener, useCapture) {
if (elem.addEventListener) {
elem.addEventListener(type, listener, useCapture);
} else if (elem.attachEvent) elem.attachEvent('on' + type, listener);
};
var _removeListener = function(elem, type, listener, useCapture) {
if (elem.removeEventListener) {
elem.removeEventListener(type, listener, useCapture);
} else if (elem.detachEvent) elem.detachEvent('on' + type, listener);
};
var _isIE6 = /*#cc_on#if(#_jscript_version == 5.6)!#end#*/false;
// Build the generic calendar container
this.elem = false;
this.cal = document.createElement('div');
this.cal.id = "calendarSelector";
var table = document.createElement('table');
table.cellSpacing = 1;
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var td = document.createElement('td');
td.appendChild(document.createTextNode((_isIE6) ? "<<" : "\u25C2\u25C2"));
td.onclick = function() {
if (this.className != "disabled") {
self.point.setFullYear(self.point.getFullYear() - 1);
self.build(); } };
tr.appendChild(td);
var th = document.createElement('th');
th.colSpan = 5;
var strong = document.createElement('strong');
strong.appendChild(document.createTextNode((_isIE6) ? "<" : "\u25C2"));
strong.onclick = function() {
if (this.className != "disabled") {
self.point.setMonth(self.point.getMonth() - 1);
self.build(); } };
th.appendChild(strong);
var em = document.createElement('em');
em.appendChild(document.createTextNode((_isIE6) ? ">" : "\u25B8"));
em.onclick = function() {
if (this.className != "disabled") {
self.point.setMonth(self.point.getMonth() + 1);
self.build(); } };
th.appendChild(em);
var span = document.createElement('span');
span.appendChild(document.createTextNode("\u2014"));
th.appendChild(span);
tr.appendChild(th);
var td = document.createElement('td');
td.appendChild(document.createTextNode((_isIE6) ? ">>" : "\u25B8\u25B8"));
td.onclick = function() {
if (this.className != "disabled") {
self.point.setFullYear(self.point.getFullYear() + 1);
self.build(); } };
tr.appendChild(td);
thead.appendChild(tr);
table.appendChild(thead);
var tfoot = document.createElement("tfoot");
var tr = document.createElement('tr');
var td = document.createElement('td');
td.colSpan = 2;
td.appendChild(document.createTextNode('Today'));
td.onclick = function() { self.hide(self.date(self.format)); };
tr.appendChild(td);
var td = document.createElement('td');
td.colSpan = 3;
td.appendChild(document.createTextNode('Cancel'));
td.onclick = function() { self.hide(false); };
tr.appendChild(td);
var td = document.createElement('td');
td.colSpan = 2;
td.appendChild(document.createTextNode('Clear'));
td.onclick = function() { self.hide(""); };
tr.appendChild(td);
tfoot.appendChild(tr);
table.appendChild(tfoot);
table.appendChild(this.cal.tBody = document.createElement('tbody'));
this.cal.appendChild(table);
this.cal.tHeads = thead.rows[0].cells;
this.cal.onselectstart = function() { return false; };
this.cal.unselectable = "on";
this.cal.onclick = function(e) {
e = e || event;
if (e.stopPropagation) { e.stopPropagation(); } else e.cancelBubble = true;
};
if (window.opera) this.cal.onmousedown = function() { return false; };
// ***** Apply listeners to applicable inputs
_addListener(window, 'load', function() {
for (var x = 0, inputs = document.getElementsByTagName('input'), val; x < inputs.length; x++) {
if (inputs[x].getAttribute('type') == "date") {
inputs[x].type = "text";
inputs[x].readOnly = "readonly";
inputs[x].onclick = function() { self.show(this); };
if (val = this.parse(inputs[x].value, false, "Y-m-d")) {
var mindt = this.parse(inputs[x].getAttribute('min'), false, "Y-m-d");
var maxdt = this.parse(inputs[x].getAttribute('max'), false, "Y-m-d");
if (mindt && val < mindt) val = mindt;
if (maxdt && val > maxdt) val = maxdt;
inputs[x].value = this.date(this.format, val);
} else inputs[x].value = "";
}
}
}, false);
})();
Then the line of HTML on the page is:
<input name="FromDate" type="date" value="<?php echo 'startdate'; ?>" size="16">
However the script forces the value to be blank.
When the page opens the "startdate" flashes momentarily and then reverts to blank (when the JavaScript has fully loaded).
If I comment out the line to the script, "startdate" appears in the box, no problem.
So it seems that something in the JavaScript reduces the value of the input field to blank or null. As I don't understand JavaScript at all, I hope someone can guide me to the line that needs to be changed.
I figured that there is a bug in the plugin (else it should work as #U and me mentioned).
But as you are already displaying value from php, you can simply comment out the 5th line from the last(else part).
You can replace the php variable startdate into the format of Y-m-d.

Categories

Resources