I am new to JavaScript and i have written a function that refreshes nodes on a web age every 5 seconds. I load a json file of 68 bytes in size and parses the html changing data.
After about 20 second the age freezes and slowing down the browser, also the class changes are not happening.
I don't know if i have a memory leak or if i should just get the server to send the data.
setInterval(function() {
$.getJSON("/Assets/inplay.json", function(data){
var j_data = JSON.parse(data);
var Curr = [];
$.each(j_data, function(key, value){
Curr.push(value._id.$oid);
chk = document.getElementById('HT-'+value._id.$oid);
if (chk == null){
$('#in-play').append(addRow(value));
} else {
var prefixes = ['GT-', 'HG-', 'HDA-', 'HA-', 'HP-', 'HOT-', 'HOffT-', 'HPI-', 'Fav-', 'AG-', 'ADA-', 'AA-', 'AP-', 'AOT-', 'AOffT-', 'API-', 'HMO-', '025-', '035-', '045-', 'AMO-', 'U25-', 'U35-', 'U45-', 'DMO-'];
var values = [value.Stats[0].gt, value.Stats[0].hg, chkVal(value.Stats[0],'Dangerous_Attacks', 0), chkVal(value.Stats[0], 'Attacks', 0), chkVal(value.Stats[0], 'Possession', 0), chkVal(value.Stats[0], 'On_Target', 0), chkVal(value.Stats[0], 'Off_Target', 0), chkVal2(value.HomePI, 'PI'), chkVal3(value.Fav), value.Stats[0].ag, chkVal(value.Stats[0], 'Dangerous_Attacks', 1), chkVal(value.Stats[0], 'Attacks', 1), chkVal(value.Stats[0], 'Possession', 1), chkVal(value.Stats[0], 'On_Target', 1), chkVal(value.Stats[0], 'Off_Target', 1), chkVal2(value.AwayPI, 'PI'), marketsFunc(value, "MATCH_ODDS", 0), marketsFunc(value, "OVER_UNDER_25", 1), marketsFunc(value, "OVER_UNDER_35", 1), marketsFunc(value, "OVER_UNDER_45", 1), marketsFunc(value, "MATCH_ODDS", 1), marketsFunc(value, "OVER_UNDER_25", 0), marketsFunc(value, "OVER_UNDER_35", 0), marketsFunc(value, "OVER_UNDER_45", 0), marketsFunc(value, "MATCH_ODDS", 2)];
for (var i = 0, len = prefixes.length; i < len; i++) {
if (values[i] != null && document.getElementById(prefixes[i]+value._id.$oid) != null) {
//console.log(prefixes[i]+value._id.$oid);
//console.log(values[i]);
if (prefixes[i] == 'GT-' && value.Tactics != null){
if(value.Tactics.indexOf("HT-LTD") != -1 && values[i] == '45:00') {
class_n = document.getElementById('HT-'+value._id.$oid).classList;
class_n.add('HT-LTD');
class_n = document.getElementById('AT-'+value._id.$oid).classList;
class_n.add('HT-LTD');
} else if (classArr.indexOf("HT-LTD") != -1 && values[i] != '45:00') {
class_n = document.getElementById('HT-'+value._id.$oid).classList;
class_n.remove('HT-LTD');
class_n = document.getElementById('AT-'+value._id.$oid).classList;
class_n.remove('HT-LTD');
}
}
if (prefixes[i] == 'HPI-' && values[i] > 6) {
class_n = document.getElementById('HT-'+value._id.$oid).classList;
class_n.add('HI-PRESSURE');
}
if (prefixes[i] == 'API-' && values[i] > 6) {
//console.log('bob');
class_n = document.getElementById('AT-'+value._id.$oid).classList;
class_n.add('HI-PRESSURE');
}
if (prefixes[i] == 'HG-' && values[i] != document.getElementById(prefixes[i]+value._id.$oid).innerHTML) {
document.getElementById('HG-'+value._id.$oid).className = 'GOAL';
}
if (prefixes[i] == 'AG-' && values[i] != document.getElementById(prefixes[i]+value._id.$oid).innerHTML) {
document.getElementById('AG-'+value._id.$oid).className = 'GOAL';
}
if (prefixes[i] == 'HG-' && document.getElementById('HG-'+value._id.$oid).className == 'GOAL') {
document.getElementById('HG-'+value._id.$oid).className = 'OLD-GOAL';
}
if (prefixes[i] == 'AG-' && document.getElementById('AG-'+value._id.$oid).className == 'GOAL') {
document.getElementById('AG-'+value._id.$oid).className = 'OLD-GOAL';
}
if (prefixes[i] == 'HG-' && document.getElementById('HG-'+value._id.$oid).className == 'OLD-GOAL') {
document.getElementById('HG-'+value._id.$oid).className = '';
}
if (prefixes[i] == 'AG-' && document.getElementById('AG-'+value._id.$oid).className == 'OLD-GOAL') {
document.getElementById('AG-'+value._id.$oid).className = '';
}
if (prefixes[i] == 'HPI-' && values[i] < 7) {
class_n = document.getElementById('HT-'+value._id.$oid).classList;
class_n.remove('HI-PRESSURE');
}
if (prefixes[i] == 'API-' && values[i] , 7) {
class_n = document.getElementById('AT-'+value._id.$oid).classList;
class_n.remove('HI-PRESSURE');
}
//console.log('ya');
document.getElementById(prefixes[i]+value._id.$oid).innerHTML = values[i];
}
}
}
});
var myGames = [];
var cl = '';
var n = [];
var table = document.getElementById("in-play");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
if (row.className == 'even') {
n = row.id.split('-');
cl = n[n.length - 1];
myGames.push(cl);
//console.log(cl);
}
}
//console.log(myGames);
for(var i = 0; i < myGames.length; i++) {
if (Curr.indexOf(myGames[i]) === -1 && myGames[i] != ""){
//console.log(myGames[i]);
var row = document.getElementById('HT-'+myGames[i]);
if (row != null) {
row.parentNode.removeChild(row);
}
row = document.getElementById('AT-'+myGames[i]);
if (row != null) {
row.parentNode.removeChild(row);
}
var tr = document.getElementsByClassName('market-'+myGames[i]);
var table = document.getElementById('in-play');
for(var i = tr.length - 1; i >= 0; i--){
table.deleteRow(tr[i].rowIndex);
}
tr = document.getElementsByClassName('form-'+myGames[i]);
table = document.getElementById('in-play');
for(var i = tr.length - 1; i >= 0; i--){
table.deleteRow(tr[i].rowIndex);
}
}
}
});
}, 5000);
Thank you for your time.
Related
I am working on node js and mysql here i am using profile incomplete or complete logic so i have to check all the fields or empty or not so i have 28 fields i have used 28 if else can we make shorter code.
Here my code
so how we can reduce my code if we can reduce our code please share your solution.
Here no error this code is correct But I need to make shorter code it will be good.
let points = 0;
let point1 = 0;
let point2 = 0;
let point3 = 0;
let point4 = 0;
let point5 = 0;
let point6 = 0;
let point7 = 0;
let point8 = 0;
let point9 = 0;
let point10 = 0;
let point11 = 0;
let point12 = 0;
let point13 = 0;
let point14 = 0;
let point15 = 0;
let point16 = 0;
let point17 = 0;
let point18 = 0;
let point19 = 0;
let point20 = 0;
let point21 = 0;
let point22 = 0;
let point23 = 0;
let point24 = 0;
let point25 = 0;
let point26 = 0;
if (profileRes[0].username == null || profileRes[0].username == "") {
point1 = points + 10;
} else if (profileRes[0].username != null || profileRes[0].username != "") {
point1 = points += 0;
}
if (profileRes[0].phone == null || profileRes[0].phone == "") {
point2 = points + 10;
} else if (profileRes[0].phone != null || profileRes[0].phone != "") {
point2 = points += 0;
}
if (profileRes[0].email == null || profileRes[0].email == "") {
point3 = points + 10;
} else if (profileRes[0].email != null || profileRes[0].email != "") {
point3 = points += 0;
}
if (profileRes[0].company_name == null || profileRes[0].company_name == "") {
point4 = points + 10;
} else if (profileRes[0].company_name != null || profileRes[0].company_name != "") {
point4 = points += 0;
}
if (profileRes[0].profile_description == null || profileRes[0].profile_description == "") {
point5 = points + 10;
} else if (profileRes[0].profile_description != null || profileRes[0].profile_description != "") {
point5 = points += 0;
}
if (profileRes[0].short_description == null || profileRes[0].short_description == "") {
point6 = points + 10;
} else if (profileRes[0].short_description != null || profileRes[0].short_description != "") {
point6 = points += 0;
}
if (profileRes[0].company_url == null || profileRes[0].company_url == "") {
point7 = points + 10;
} else if (profileRes[0].company_url != null || profileRes[0].company_url != "") {
point7 = points += 0;
}
if (profileRes[0].company_linkedin == null || profileRes[0].company_linkedin == "") {
point8 = points + 10;
} else if (profileRes[0].company_linkedin != null || profileRes[0].company_linkedin != "") {
point8 = points += 0;
}
if (profileRes[0].company_instagram == null || profileRes[0].company_instagram == "") {
point9 = points + 10;
} else if (profileRes[0].company_instagram != null || profileRes[0].company_instagram != "") {
point9 = points += 0;
}
if (profileRes[0].company_facebook == null || profileRes[0].company_facebook == "") {
point10 = points + 10;
} else if (profileRes[0].company_facebook != null || profileRes[0].company_facebook != "") {
point10 = points += 0;
}
if (profileRes[0].number_of_employees == null || profileRes[0].number_of_employees == "") {
point11 = points + 10;
} else if (profileRes[0].number_of_employees != null || profileRes[0].number_of_employees != "") {
point11 = points += 0;
}
if (profileRes[0].company_logo == null || profileRes[0].company_logo == "") {
point12 = points + 10;
} else if (profileRes[0].company_logo != null || profileRes[0].company_logo != "") {
point12 = points += 0;
}
if (profileRes[0].founding_year == null || profileRes[0].founding_year == "") {
point13 = points + 10;
} else if (profileRes[0].founding_year != null || profileRes[0].founding_year != "") {
point13 = points += 0;
}
if (profileRes[0].is_profile_published == null || profileRes[0].is_profile_published == "") {
point14 = points + 10;
} else if (profileRes[0].is_profile_published != null || profileRes[0].is_profile_published != "") {
point14 = points += 0;
}
if (profileRes[0].legal_name == null || profileRes[0].legal_name == "") {
point15 = points + 10;
} else if (profileRes[0].legal_name != null || profileRes[0].legal_name != "") {
point15 = points += 0;
}
if (profileRes[0].billing_address == null || profileRes[0].billing_address == "") {
point16 = points + 10;
} else if (profileRes[0].billing_address != null || profileRes[0].billing_address != "") {
point16 = points += 0;
}
if (profileRes[0].zip_code == null || profileRes[0].zip_code == "") {
point17 = points + 10;
} else if (profileRes[0].zip_code != null || profileRes[0].zip_code != "") {
point17 = points += 0;
}
if (profileRes[0].vat_number == null || profileRes[0].vat_number == "") {
point18 = points + 10;
} else if (profileRes[0].vat_number != null || profileRes[0].vat_number != "") {
point18 = points += 0;
}
if (profileRes[0].sdi_codex == null || profileRes[0].sdi_codex == "") {
point19 = points + 10;
} else if (profileRes[0].sdi_codex != null || profileRes[0].sdi_codex != "") {
point19 = points += 0;
}
if (profileRes[0].benefits == null || profileRes[0].benefits == "") {
point20 = points + 10;
} else if (profileRes[0].benefits != null || profileRes[0].benefits != "") {
point20 = points += 0;
}
if (profileRes[0].category == null || profileRes[0].category == "") {
point21 = points + 10;
} else if (profileRes[0].category != null || profileRes[0].category != "") {
point21 = points += 0;
}
if (profileRes[0].branch == null || profileRes[0].branch == "") {
point22 = points + 10;
} else if (profileRes[0].branch != null || profileRes[0].branch != "") {
point22 = points += 0;
}
if (profileRes[0].coreActivities == null || profileRes[0].coreActivities == "") {
point23 = points + 10;
} else if (profileRes[0].coreActivities != null || profileRes[0].coreActivities != "") {
point23 = points += 0;
}
if (profileRes[0].districts == null || profileRes[0].districts == "") {
point24 = points + 10;
} else if (profileRes[0].districts != null || profileRes[0].districts != "") {
point24 = points += 0;
}
if (profileRes[0].legalFormCompany == null || profileRes[0].legalFormCompany == "") {
point25 = points + 10;
} else if (profileRes[0].legalFormCompany != null || profileRes[0].legalFormCompany != "") {
point25 = points += 0;
}
if (profileRes[0].commune == null || profileRes[0].commune == "") {
point26 = points + 10;
} else if (profileRes[0].commune != null || profileRes[0].commune != "") {
point26 = points += 0;
}
else {
}
let pint = point1 + point2 + point3 + point4 + point5 + point6 + point7 + point8 + point9 + point10 +point11 + point12 + point13 + point14 + point15 + point16 + point17 + point18 + point19 + point20 + point21 + point22 + point23 + point24 + point25 + point26;
let percentage = (pint * 100) / 260;
Should all keys in the profileRes[0] have a corresponding points variable? If yes, then something like this might work. This solution will put all of your points into one object instead of a list of variables:
const pointsMap = Object.entries(profileRes[0]).reduce((acc, [key, value]) => {
acc[key] = !!value ? 0 : 10
return acc
}, {})
// returns an object that has key/value pairs accessible by the profileRes[0] keys
// for example, {username: 10, email: 0, phone: 10...}
Note, the above answer uses !!value to determine if the value is truthy. This means values like null and "" will fail. undefined will also fail this check. If a key in profileRes[0] can be undefined and undefined should be considered a valid value, the line can change to be the following instead:
acc[key] = (value === null || value === "") ? 10 : 0
You can remove all the points variables
let points = 0;
for (let key in profileRes[0]) {
if (profileRes[0][key] === null || profileRes[0][key] === '') {
points += 10;
} else {
points += 0;
}
}
let percentage = (points * 100) / 260;
While we adding HTML into the HTML output render has in the DIV. If we added something like following
<div class="test" w3-include-html="template_build/header/header-classic.html"></div>
But the output render has incldued that
<div class="test">MY INCLUDED CONTENT</div>
I want to remove that div class="test" on rendering process on w3data.js.
Can someone help me?
Snippet 1 features a simple function that removes any given attribute from any given element. Snippet 2 is the w3data.js with an extra line at 126:
elmnt.removeAttribute("class");
You may use either one to get the same result
SNIPPET 1
removeAttr(".test", "class");
function removeAttr(target, attribute) {
var target = document.querySelector(target);
target.removeAttribute(attribute);
}
.test { color:red }
<div class="test">THIS CONTENT SHOULD BE BLACK TEXT, NOT RED</div>
SNIPPET 2
/* W3Data ver 1.31 by W3Schools.com */
var w3DataObject = {};
function w3DisplayData(id, data) {
var htmlObj, htmlTemplate, html, arr = [],
a, l, rowClone, x, j, i, ii, cc, repeat, repeatObj, repeatX = "";
htmlObj = document.getElementById(id);
htmlTemplate = w3InitTemplate(id, htmlObj);
html = htmlTemplate.cloneNode(true);
arr = w3GetElementsByAttribute(html, "w3-repeat");
l = arr.length;
for (j = (l - 1); j >= 0; j -= 1) {
cc = arr[j].getAttribute("w3-repeat").split(" ");
if (cc.length == 1) {
repeat = cc[0];
} else {
repeatX = cc[0];
repeat = cc[2];
}
arr[j].removeAttribute("w3-repeat");
repeatObj = data[repeat];
if (repeatObj && typeof repeatObj == "object" && repeatObj.length != "undefined") {
i = 0;
for (x in repeatObj) {
i += 1;
rowClone = arr[j];
rowClone = w3NeedleInHaystack(rowClone, "element", repeatX, repeatObj[x]);
a = rowClone.attributes;
for (ii = 0; ii < a.length; ii += 1) {
a[ii].value = w3NeedleInHaystack(a[ii], "attribute", repeatX, repeatObj[x]).value;
}
(i === repeatObj.length) ? arr[j].parentNode.replaceChild(rowClone, arr[j]): arr[j].parentNode.insertBefore(rowClone, arr[j]);
}
} else {
console.log("w3-repeat must be an array. " + repeat + " is not an array.");
continue;
}
}
html = w3NeedleInHaystack(html, "element");
htmlObj.parentNode.replaceChild(html, htmlObj);
function w3InitTemplate(id, obj) {
var template;
template = obj.cloneNode(true);
if (w3DataObject.hasOwnProperty(id)) {
return w3DataObject[id];
}
w3DataObject[id] = template;
return template;
}
function w3GetElementsByAttribute(x, att) {
var arr = [],
arrCount = -1,
i, l, y = x.getElementsByTagName("*"),
z = att.toUpperCase();
l = y.length;
for (i = -1; i < l; i += 1) {
if (i == -1) {
y[i] = x;
}
if (y[i].getAttribute(z) !== null) {
arrCount += 1;
arr[arrCount] = y[i];
}
}
return arr;
}
function w3NeedleInHaystack(elmnt, typ, repeatX, x) {
var value, rowClone, pos1, haystack, pos2, needle = [],
needleToReplace, i, cc, r;
rowClone = elmnt.cloneNode(true);
pos1 = 0;
while (pos1 > -1) {
haystack = (typ == "attribute") ? rowClone.value : rowClone.innerHTML;
pos1 = haystack.indexOf("{{", pos1);
if (pos1 === -1) {
break;
}
pos2 = haystack.indexOf("}}", pos1 + 1);
needleToReplace = haystack.substring(pos1 + 2, pos2);
needle = needleToReplace.split("||");
value = undefined;
for (i = 0; i < needle.length; i += 1) {
needle[i] = needle[i].replace(/^\s+|\s+$/gm, ''); //trim
//value = ((x && x[needle[i]]) || (data && data[needle[i]]));
if (x) {
value = x[needle[i]];
}
if (value == undefined && data) {
value = data[needle[i]];
}
if (value == undefined) {
cc = needle[i].split(".");
if (cc[0] == repeatX) {
value = x[cc[1]];
}
}
if (value == undefined) {
if (needle[i] == repeatX) {
value = x;
}
}
if (value == undefined) {
if (needle[i].substr(0, 1) == '"') {
value = needle[i].replace(/"/g, "");
} else if (needle[i].substr(0, 1) == "'") {
value = needle[i].replace(/'/g, "");
}
}
if (value != undefined) {
break;
}
}
if (value != undefined) {
r = "{{" + needleToReplace + "}}";
if (typ == "attribute") {
rowClone.value = rowClone.value.replace(r, value);
} else {
w3ReplaceHTML(rowClone, r, value);
}
}
pos1 = pos1 + 1;
}
return rowClone;
}
function w3ReplaceHTML(a, r, result) {
var b, l, i, a, x, j;
if (a.hasAttributes()) {
b = a.attributes;
l = b.length;
for (i = 0; i < l; i += 1) {
if (b[i].value.indexOf(r) > -1) {
b[i].value = b[i].value.replace(r, result);
}
}
}
x = a.getElementsByTagName("*");
l = x.length;
a.innerHTML = a.innerHTML.replace(r, result);
}
}
function w3IncludeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
elmnt.removeAttribute("w3-include-html");
elmnt.removeAttribute("class"); // Add this expression
w3IncludeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
function w3Http(target, readyfunc, xml, method) {
var httpObj;
if (!method) {
method = "GET";
}
if (window.XMLHttpRequest) {
httpObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpObj) {
if (readyfunc) {
httpObj.onreadystatechange = readyfunc;
}
httpObj.open(method, target, true);
httpObj.send(xml);
}
}
I have a text box that will only show half of the text inputted, unless the text box is a bigger size. Before I type, the cursor is half way showing, when I'm typing, it is normal, then after I type, it goes back to only half way showing. The text box is attached to Java Script that makes it so the inputted amount automatically turns into a dollar amount, would that affect it?
JavaScript:
$(document).ready(function () {
$("input[type=text].currenciesOnly").live('keydown', currenciesOnly)
.live('blur', function () {
$(this).formatCurrency();
});
});
// JavaScript I wrote to limit what types of input are allowed to be keyed into a textbox
var allowedSpecialCharKeyCodes = [46, 8, 37, 39, 35, 36, 9];
var numberKeyCodes = [44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var commaKeyCode = [188];
var decimalKeyCode = [190, 110];
function numbersOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function numbersAndCommasOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function decimalsOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function currenciesOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
// Allow for $
if (!legalKeyCode && event.shiftKey && event.keyCode == 52) legalKeyCode = true;
if (legalKeyCode === false) event.preventDefault();
}
// jQuery formatCurrency plugin... see http://code.google.com/p/jquery-formatcurrency/
(function ($) {
$.formatCurrency = {};
$.formatCurrency.regions = [];
$.formatCurrency.regions[""] = {
symbol: "$",
positiveFormat: "%s%n",
negativeFormat: "(%s%n)",
decimalSymbol: ".",
digitGroupSymbol: ",",
groupDigits: true
};
$.fn.formatCurrency = function (destination, settings) {
if (arguments.length == 1 && typeof destination !== "string") {
settings = destination;
destination = false;
}
var defaults = {
name: "formatCurrency",
colorize: false,
region: "",
global: true,
roundToDecimalPlace: 2,
eventOnDecimalsEntered: false
};
defaults = $.extend(defaults, $.formatCurrency.regions[""]);
settings = $.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
$this = $(this);
var num = "0";
num = $this[$this.is("input, select, textarea") ? "val" : "html"]();
if (num.search("\\(") >= 0) {
num = "-" + num;
}
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (isNaN(num)) {
num = num.replace(settings.regex, "");
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
if (isNaN(num)) {
num = "0";
}
}
var numParts = String(num).split(".");
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : "0");
var originalDecimals = decimals;
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (settings.roundToDecimalPlace >= 0) {
decimals = parseFloat("1." + decimals);
decimals = decimals.toFixed(settings.roundToDecimalPlace);
if (decimals.substring(0, 1) == "2") {
num = Number(num) + 1;
}
decimals = decimals.substring(2);
}
num = String(num);
if (settings.groupDigits) {
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ;
i++) {
num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
}
}
if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
num += settings.decimalSymbol + decimals;
}
var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
var money = format.replace(/%s/g, settings.symbol);
money = money.replace(/%n/g, num);
var $destination = $([]);
if (!destination) {
$destination = $this;
} else {
$destination = $(destination);
}
$destination[$destination.is("input, select, textarea") ? "val" : "html"](money);
if (hasDecimals && settings.eventOnDecimalsEntered && originalDecimals.length > settings.roundToDecimalPlace) {
$destination.trigger("decimalsEntered", originalDecimals);
}
if (settings.colorize) {
$destination.css("color", isPositive ? "black" : "red");
}
});
};
$.fn.toNumber = function (settings) {
var defaults = $.extend({
name: "toNumber",
region: "",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
var method = $(this).is("input, select, textarea") ? "val" : "html";
$(this)[method]($(this)[method]().replace("(", "(-").replace(settings.regex, ""));
});
};
$.fn.asNumber = function (settings) {
var defaults = $.extend({
name: "asNumber",
region: "",
parse: true,
parseType: "Float",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
settings.parseType = validateParseType(settings.parseType);
var method = $(this).is("input, select, textarea") ? "val" : "html";
var num = $(this)[method]();
num = num ? num : "";
num = num.replace("(", "(-");
num = num.replace(settings.regex, "");
if (!settings.parse) {
return num;
}
if (num.length === 0) {
num = "0";
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
return window["parse" + settings.parseType](num);
};
function getRegionOrCulture(region) {
var regionInfo = $.formatCurrency.regions[region];
if (regionInfo) {
return regionInfo;
} else {
if (/(\w+)-(\w+)/g.test(region)) {
var culture = region.replace(/(\w+)-(\w+)/g, "$1");
return $.formatCurrency.regions[culture];
}
}
return null;
}
function validateParseType(parseType) {
switch (parseType.toLowerCase()) {
case "int":
return "Int";
case "float":
return "Float";
default:
throw "invalid parseType";
}
}
function generateRegex(settings) {
if (settings.symbol === "") {
return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
} else {
var symbol = settings.symbol.replace("$", "\\$").replace(".", "\\.");
return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
}
}
})(jQuery);
Textbox:
<input type="text" class="currenciesOnly" />
Code from free open source site
With help from #Eyal and #LeoFarmer somewhere within bootstrap, the line-height was affecting it. So I set line-height to normal in the css for the textbox:
.currenciesOnly {
line-height: normal;
}
I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5
I am trying to turn this code into a correct for loop statement, so that I can save my repetitions. I have tried my best to get it done, but I just don't know how I can write it correctly:
function myProg() {
var luckyNumber = 3;
var luckyNumber2 = 5;
var luckyNumber3 = 8;
var firstInput = document.luckForm.numberBox.value;
var secondInput = document.luckForm.numberBox2.value;
var thirdInput = document.luckForm.numberBox3.value;
var temp = '';
if (firstInput == luckyNumber && secondInput == luckyNumber2 && thirdInput == luckyNumber3 || firstInput == luckyNumber && secondInput == luckyNumber3 && thirdInput == luckyNumber2 || firstInput == luckyNumber2 && secondInput == luckyNumber3 && thirdInput == luckyNumber || firstInput == luckyNumber2 && secondInput == luckyNumber && thirdInput == luckyNumber3 || firstInput == luckyNumber3 && secondInput == luckyNumber && thirdInput == luckyNumber2 || firstInput == luckyNumber3 && secondInput == luckyNumber2 && thirdInput == luckyNumber)
{
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!');
}
}
try something like this:
Array.prototype.getDuplicates = function() {
var cache = {}, results = [], that = this;
that.forEach(function(item, index) {
if(!cache.hasOwnProperty(item) && that.lastIndexOf(item) > index) {
results.push(item);
}
cache[item] = true;
});
return results;
}
var answers = [luckyNumber, luckyNumber2, luckyNumber3];
var indexes = [answers.indexOf(firstInput), answers.indexOf(secondInput), answers.indexOf(thirdInput)];
if(indexes.indexOf(-1) === -1 && indexes.getDuplicates().length === 0) {
// alert("Whatever");
}
Here's an example without using array. Input check was added.
function myProg() {
var numbersToMatch = 3;
var luckyNumbers = {n1: 3, n2: 5, n3: 8};
var firstInput = parseInt(document.luckForm.numberBox.value);
var secondInput = parseInt(document.luckForm.numberBox2.value);
var thirdInput = parseInt(document.luckForm.numberBox3.value);
if (isNaN(firstInput) || isNaN(secondInput) || isNaN(thirdInput)) {
alert('All inputs must be numbers!');
return;
}
var inputs = {n1: firstInput, n2: secondInput, n3: thirdInput};
var matches = {n1: false, n2: false, n3: false};
for (var i in inputs) {
for (var j in luckyNumbers) {
if ((!matches[j]) && (luckyNumbers[j] == inputs[i])) {
matches[j] = true;
numbersToMatch--;
break;
}
}
}
if (numbersToMatch == 0) {
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!');
}
}