jQuery recursive wildcard selector from array and array push dynamically - javascript

Link to jsFiddle
I have many elements containing text in which I am using parseInt() to grab the values from a specific number of elements (based on the current month) and a specific selector wildcard and push those values into one of six arrays for use elsewhere. I am trying to clean up the code and make a compact loop to complete all of this.
I am able to get everything to work if I use six separate for loops, but I thought I might try to see if it is able to be done in one single loop.
So in the for loop below, I am trying to make the jQuery wildcard selector for the element ID be the current value of i (from statusArray) by trying something like $('[id*=statusArray[i]]) but that doesn't seem to be working.
Then I would like to push the data into the predefined appropriate array by something like statusArray[i]Array.push(...) but that doesn't work either. I've tried concatenating various ways but can't seem to get it to work.
Any help would be appreciated! Thank you in advance!
HTML:
<div id="jan_connected"></div> <!-- left empty to test for NaN -->
<div id="jan_busy">100</div>
<div id="jan_noanswer">100</div>
<div id="jan_abandoned">100</div>
<div id="feb_minutes">100</div>
<div id="feb_totals_calls_c">100</div>
<div id="feb_connected">100</div>
<div id="feb_busy">100</div>
<div id="feb_noanswer">100</div>
<div id="feb_abandoned">100</div>
Javascript:
var connectedArray = [];
var busyArray = [];
var noanswerArray = [];
var abandonedArray = [];
var minutesArray = [];
var callsArray = [];
// var date = new Date();
// var dateNumber = 1 + date.getMonth();
var dateNumber = 2;
var statusArray = ['minutes', 'total_calls', 'connected', 'busy', 'noanswer', 'abandoned']
for (i=0; i<dateNumber; i++) {
// Below I would like the id* to equal the current value of the statusArray iteration
if (isNaN(parseInt($('[id*=statusArray[i]]').slice(i).html()))) {
statusArray[i]Array.push("0"); // Trying to push into the appropriate array dynamically
} else {
statusArray[i]Array.push(parseInt($('[id*=statusArray[i]]').slice(i).html()));
}
}

You have syntax errors in couple of places..
this line
$('[id*=statusArray[i]]')
supposed to be
$('[id*=' + statusArray[i] + ']')
And
statusArray[i] Array.push("0");
should be
statusArray[i].push("0");
Push method is available on a Array , but statusArray[i] is not an array but a string.
Looks like you are looking for something like this
var connectedArray = [];
busyArray = [];
noanswerArray = [];
abandonedArray = [];
minutesArray = [];
callsArray = [];
dateNumber = 2;
statusArray = ['minutes', 'total_calls', 'connected', 'busy', 'noanswer', 'abandoned'];
var obj = {
'minutes': minutesArray,
'totals_calls': callsArray,
'connected': connectedArray,
'busy': busyArray,
'noanswer': noanswerArray,
'abandoned': abandonedArray
};
for (i = 0; i < statusArray.length; i++) {
$('[id*="' + statusArray[i] + '"]').each(function () {
var val = $(this).html();
if (isNaN(parseInt(val))) {
obj[statusArray[i]].push("0");
} else {
obj[statusArray[i]].push(val);
}
});
}
console.log('Minutes Array: ' + obj['minutes']);
console.log('Total Calls Array: ' + obj['totals_calls']);
console.log('Connected Array: ' + obj['connected']);
console.log('No Answer Array: ' + obj['noanswer']);
console.log('Abandoned Array: ' + obj['abandoned']);
console.log('Busy Array: ' + obj['busy']);
Check Fiddle

Related

How to change specific values in a table created in javascript by pressing a button

Does anyone here know how I can change the value of "list4" when I have created a HTML table like so:
var obj = { list1, list2, list3, list4, list5 };
var newArray = [];
Object.keys(obj).forEach( (o) => newArray.push(obj[o]));
newArray.forEach(function(items) {
var row = document.createElement("tr");
items.forEach(function(item) {
var cell = document.createElement("td");
cell.textContent = item;
row.appendChild(cell);
});
table.appendChild(row);
});
I have extracted the 5 list elements out of a larger array by using this method:
var list1 = myArray.map(a => a.list1);
var list2 = myArray.map(a => a.list2);
var list3 = myArray.map(a => a.list3);
var list4 = myArray.map(a => a.list4);
var list5 = myArray.map(a => a.list5);
And I would like to change the value of all of the list elements in "list 4" to the existing values divided by 2.2046:
I have made a for-loop and changed the values to the new values:
var newValues = myArray.map(a => a.list4);
for (var i = 0; i < newValues.length; i++) {
newValues[i] = (newValues[i]/2.2046).toFixed(1);
}
Does anyone know how I can incorporate the last code so that I, by pressing a button with the id="metric", can make all the existing values change to the new values? I thinking maybe innterHTML could help, but I do not know how to get the specific values of list4.. Thank you for any help!
Bonus:
I have tried everything but have not succeeded in turning a string of "5' 6\"" into actual numbers as I also have to change these to metric values, possible anyone here knows?:) Thank you!
Create an array of cell elements in the same scope as your list. That way, you write something like cell[0].textContent = value whenever you want.
Separate updating the HTML in a new function. Clear the HTML by using remove(), then update by using .appendChild(cell[0]) to add the new values.
As for changing the string to numbers, here is an idea:
let number = "5' 6\"";
let div = document.getElementById("test");
let decimalValue = imperialToDecimal(number);
div.innerHTML = number + " becomes " + decimalValue;
function imperialToDecimal(measurement) {
let indxFeet = measurement.indexOf("'");
let indxInches = measurement.indexOf("\"");
let feet = measurement.substring(0, indxFeet);
let inches = measurement.substring(indxFeet + 1, indxInches);
return footAndInchToMeter(feet, inches);
}
function footAndInchToMeter(feet, inches) {
feet = feet/3.2808;
inches = inches/39.370;
return feet + inches;
}
<div id="test"></div>
This is the basic code that doesn't contain correction for when there is no ' or " symbol (but you can figure that out, I'm sure :).

Syntax to build object properties in loop - javascript

I would like to loop through a list of objects and display one property on a graph on the page but I can't seem to get the right syntax to get this data in a loop.
Without the loop this gives an idea of what I want to do:
document.getElementById("v1").innerHTML = zone1.sensor;
document.getElementById("v2").innerHTML = zone2.sensor;
document.getElementById("v3").innerHTML = zone3.sensor;
I can't figure out how to loop through the objects, something like this:
for(i = 1; i < 7; i++) {
document.getElementById("v" + i).innerHTML = ("zone" + i + ".sensor");
}
While that can be done with eval() or new Function (), that's just plain wrong. Put your values in an array and access them by index. If you absolutely have to use independent variables, do:
var arr = [zone1, zone2, zone3];
and then use
arr[i].sensor
I would go this way to avoid the use of eval:
var zone1 = new Object;
var zone2 = new Object;
var zone3 = new Object;
zone1.sensor = "sensor1";
zone2.sensor = "sensor2";
zone3.sensor = "sensor3";
var zones = [zone1, zone2, zone3];
for( var i = 1; i < 4; i++) {
document.getElementById("v" + i).innerHTML = zones[i - 1]["sensor"];
}
<div id="v1"></div>
<div id="v2"></div>
<div id="v3"></div>
Hope it helps!

JavaScript: Is this possible? using array value to display the quantity

Given this JavaScript array:
var list = [1,1,1,2,2,2,2]
I want to know how I can produce an HTML list below that has each unique item in the array and number of times that they appear in the array. I just want to know the JavaScript to produce the data, I can generate the HTML.
1 is x3
2 is x4
I'm confused about how to achieve this. Basically, similar to shopping cart quantity functionality, but using the array.
http://jsfiddle.net/37ab3k00/
Use .reduce to reduce your array to an object of quantities.
var list = [1, 1, 1, 2, 2, 2, 2];
var quantities = list.reduce(function(obj, n) {
if (obj[n]) obj[n]++;
else obj[n] = 1;
return obj;
}, {});
var ul = document.querySelector("ul");
for (var n in quantities) {
ul.appendChild(document.createElement("li")).textContent = n + " has a quantity x" + quantities[n];
}
<ul></ul>
The first argument to .reduce() is a function that gets invoked for each member in the Array.
The second argument is an object that we're going to pass along to each iteration. It gets passed as the first argument to the function we provided, and we always return it so that it always gets passed as that argument. This is called the accumulator.
The n argument to the function we provided is the value of the current member in the list. So what we do is first see if our obj has a truthy n member. If so, it must have been encountered already, so we increment it. If not, we assign it the initial value of 1 to represent the first n that was found for that value.
var list = [1,1,1,2,2,2,2]
var counts = {};
for (var i = 0; i < list.length; i++) {
counts[list[i]] = 1 + (counts[list[i]] || 0);
}
Demo: http://jsfiddle.net/famn4zcL/2/
Add to HTML
var li = '';
for (var el in counts) {
li += '<li>' + el + ' is x' + counts[el] + '</li>';
}
document.getElementById('list').innerHTML = li;
Demo: http://jsfiddle.net/famn4zcL/3/
Another way would be using array of objects (those can be easily upgraded with additional data that you probably would need building products), like so:
HTML:
<span id="display"></span>
JS (plain, no Framework):
var objects = [
{prod:0,quant:00},
{prod:1,quant:11},
{prod:2,quant:22},
{prod:3,quant:33},
{prod:4,quant:44},
{prod:5,quant:55}
];
var list_of_objects = "", display_id = document.getElementById("display");
for (var key in objects) {
if (objects.hasOwnProperty(key)) {
console.log(key);
list_of_objects += '<li>'+objects[key].prod + ' has a qtty x ' + objects[key].quant+'</li>';
}
}
console.log(list_of_objects);
display_id.innerHTML = list_of_objects;
So you could easily upgrade product data with new info, like:
var objects = [
{prod:0,quant:00,url:"http://url00"},
{prod:1,quant:11,url:"http://url11"},
{prod:2,quant:22,url:"http://url22"},
{prod:3,quant:33,url:"http://url33"},
{prod:4,quant:44,url:"http://url44"},
{prod:5,quant:55,url:"http://url55"}
];
JSfiddle to play with: http://jsfiddle.net/7hokfmdu/

want to get textbox value

I have two textboxes which values are like:
312,315
315,313
I want to get a string with all the values, for example: 312,315,313 skipping existing values in both fields.
My code:
var firstbox = $("#firstbox").val();
var secondbox = $("#secondbox").val();
var newvalue = $(firstbox).not(secondbox).get();
console.log(newvalue);
But it's not working, how can I get my desired output using JQuery?
thanks.
You could concatenate the two, joining them with a comma.
You would then have a comma delimited string, so you could split at the comma, remove any duplicate values, then rejoin the remaining values.
Something like this:
var firstbox = $("#firstbox").val(),
secondbox = $("#secondbox").val(),
boxes = firstbox + "," + secondbox,
arr = boxes.split(","),
res = [];
$.each(arr, function(i, el){
if($.inArray(el, res) === -1){
res.push(el);
}
});
$("#res").html(res.join(",").replace(/(^,)|(,$)/g, ""));
Fiddle
Maybe this will give you a hint in the right direction:
// get comma seperated list of all values
var allValues = $('#firstbox').val() + ',' + $('#secondbox').val();
// make an array out of them
var allValuesArray = allValues.split(',');
// sort out repeated values
// by creating a new array 'distinctValues'
var distinctValues = [],
currentValue,
valuesLookup = {};
for (var i = allValuesArray.length - 1; i >= 0; i--) {
currentValue = allValuesArray[i];
if (!valuesLookup[currentValue]) {
valuesLookup[currentValue] = true;
distinctValues.push(currentValue);
}
}
// output the result to the console
console.log(distinctValues.join(','));

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

Categories

Resources