jQuery counting elements with attributes - javascript

I have a jQuery code wich is counting some divs where certain Breakfast board are found as below
var board_bb1 = $('div[data-board="Bed And Breakfast"]').length;
var board_bb2 = $('div[data-board="Breakfast"]').length;
var board_bb3 = $('div[data-board="Breakfast Buffet"]').length;
var board_bb4 = $('div[data-board="Breakfast (Full Breakfast)"]').length;
var board_bb5 = $('div[data-board="Continental Breakfast"]').length;
var board_bb8 = $('div[data-board="Bed and Breakfast"]').length;
var board_bb6 = $('div[data-board="Full Breakfast"]').length;
var board_bb7 = $('div[data-board="Breakfast (Continental Breakfast)"]').length;
var board_bb = board_bb1 + board_bb2 + board_bb3 + board_bb4 + board_bb5 + board_bb6 + board_bb7 + board_bb8;
The attributes from data-board are coming from an API service, and sometimes is breakfast sometimes is Breakfast, bed And Breakfast etc.
Is there a way to simply the above code to count all the divs who has the word Breakfast in data-board

$("div[data-board*='Breakfast']").length
The *= part will look for any attribute containing the word breakfast.
IF you are not using jQuery in your project, in modern browsers this will work to:
document.querySelectorAll("div[data-board*='Breakfast']").length;
To complete it: a cross-browser solution that will work all the way back to IE5.5
var allDivs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0, i < allDivs.length; i++)
{
if (allDivs[i].getAttribute("data-board") && allDivs[i].getAttribute("data-board").match(/Breakfast/) )
{
count++;
}
}
After this count will return the amount of divs containing the word Breakfast in the data-board attribute

You can use ~ operator
$("div[data-board~='Breakfast']").length

Related

Locating all cell's positions in google sheets

The problem is: I have big spreadsheet (more than 4500 rows) with a lot of data in the first column - for ex. with types of fruits, which are not unique, like this:
APPLE
BANANA
APRICOTS
APPLE
BLACKCURRANT
APPLE
BANANA
APRICOTS
etc.
What I need - locate each BANANA, to be able to put in cell beside some info, for ex. YES. I tried to loop solution from Locating a cell's position in google sheets using a string or an integer but for sure my code is wrong. I already spent a lot of hours to invent something, but still don't understand what I'm missing.
function test(){
var dispatch = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FRUITS");
var find = dispatch.getRange("A:A").getValues();
var name = "BANANA";
var lastRow = dispatch.getLastRow();
var n = 1;
var temp = dispatch.getRange(n, 2).getValue();
var i = 0;
while (temp != ""){
for(var n in find){
if(find[n][0] === name){break}
}
n++;
var n = n + i;
dispatch.getRange(n, 2).setValue("YES");
var temp = dispatch.getRange(n, 2).getValues();
var find = dispatch.getRange(n, 2, lastRow).getValues();
var i = n;
}
}
I will be very grateful for the help.
The code example is below:
function test(){
var dispatch = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FRUITS");
var range = dispatch.getRange(1, 1, dispatch.getLastRow(), 2);
var values = range.getValues();
values.map(function(row) {
if (row[0] == "BANANA")
row[1] = "YES";
});
range.setValues(values);
}
JS array map() method does the most part of work. We convert range values to JS array and back after mapping completes.

How to add marquee element with text to a div in javascript

I have an array of line_items which contain some text, i have 9 div with id like <div id="scroller-1"></div> and scroller-2 and so on...
what i want to do is i am iterating through array and getting text, but i want to add first element to div with scroller-1 id, second element to scroller-2 and so on like for all 9 divs. how can i do that
var trending_cat = [
["Lotto Rapid Running Shoes"],
["Paradise (English) (Paperback)"],
["Canon EOS 700D (Body with 18-135 mm Lens) DSLR Camera"],
["Huetrap Graphic Print Men's Round Neck T-Shirt"],
["Vincent chase vc 5158 silver silver reflector mirror ao12jo aviator sunglasses"],
["Orka XL Bean Bag With Bean Filling"],
['HP Compaq 15-s103TX Notebook (4th Gen Ci3 4GB 1TB Free DOS 2GB Graph) (K8T82PA)'],
['Moto G (2nd Generation) White, 16 GB'],
['Fastrack 9827PP01 Hip Hop Analog Watch - For Women'],
];
javascript:
for (var i = 0; i < trending_cat.length; i++) {
var cato = trending_cat[i][0];
}
i want to append the value like this
<marquee scrollamount="38"><strong><h1>[i][0]</h1></strong></marquee>
There are a couple of ways. If there's a CSS selector that matches the elements in the order you want to apply them, it's really easy:
var list = document.querySelectorAll("the-css-selector");
for (var i = 0; i < trending_cat.length; i++) {
list[i].innerHTML = trending_cat[i][0];
}
If you need to work with id values in the form scroller-1 through scroller-9, it's also really straightforward:
for (var i = 0; i < trending_cat.length; i++) {
document.getElementById("scroller-" + (i + 1)).innerHTML = trending_cat[i][0];
}
Both of those assume you want to interpret the strings as HTML. If you want them interpreted as pure text, cross-browser issues make it a bit more complicated (but not much).
var list = document.querySelectorAll("the-css-selector");
for (var i = 0; i < trending_cat.length; i++) {
list[i].innerHTML = "";
list[i].appendChild(document.createTextNode(trending_cat[i][0]));
}
Or with the ids:
var element;
for (var i = 0; i < trending_cat.length; i++) {
element = document.getElementById("scroller-" + (i + 1));
element.innerHTML = "";
element.appendChild(document.createTextNode(trending_cat[i][0]));
}
In both cases, we can be more succinct using Array#forEach:
var list = document.querySelectorAll("the-css-selector");
trending_cat.forEach(function(cato) {
list[i].innerHTML = "";
list[i].appendChild(document.createTextNode(cato));
});
(And similarly for the ids version.)
If you rearrange the html tag so that the marquee is in the center, you can insert the text without worrying about overwriting the h1 and strong tags. E.g.,
<strong><h1><marquee id="scroller-0" scrollamount="38"></marquee></h1></strong>
Also, your strings inside trending_cat do not have to be in separate arrays. This is fine:
var trending_cat = [
"Lotto Rapid Running Shoes",
// etc
];
You can use a for-loop to set the values:
for (var i=0; i<8; i++) {
document.getElementById("scroller-"+i).innerText = trending_cat[i];
}
Here is a running example: https://jsfiddle.net/dxv1x419/2/

How to add a large number of items to an HTML selectObject

I need to populate eight selectObject pulldown objects on a page with several thousand (8192) items each. I'm currently doing this in Javascript the only way I know how:
var iCount;
var option1;
var selectObject1 = document.getElementById('ifbchan');
for(iCount = 0; iCount < 8192; iCount++)
{
option1=document.createElement("option");
option1.text = "Out " + iCount;
option1.value=iCount;
try
{
selectObject1.add(option1, selectObject1.options[null]);
}
catch (e)
{
selectObject1.add(option1, null);
}
}
selectObject1.selectedIndex = 0;
This method works properly but is extremely slow! Each of these 8K loops takes something like 10 seconds to complete. Multiply by 8 different loops and the problem is obvious. Is there any other way to add large numbers of items to a drop down list that would be faster? Any faster alternatives to the drop down control for presenting a large list of items? Thanks for any ideas.
~Tim
I'd try the following:
var elements = ""
var i;
for(i= 0; i < 8192; i++){
elements += "<option value='"+ i + "'>Out " + i + "</option>";
}
document.getElementById("ifbchan").innerHTML = elements;
This way you only perform one action on the DOM per loop not 8000+.
Oh and here's one I prepared earlier: http://jsfiddle.net/3Ub4x/
Few things before the answer.
First of all I do not think that the best way to do this is a server side implementation. If you can do something on the client you should do this and not touch your server (if it is not security related).
Second thing - why exactly do you need 8000 elements in select list? Think as a user of your app, who would like to scroll through 8000 elements just to select his element? As it was mentioned before - autocomplete sounds much more suitable.
And right now is an answer:
Your original approach is here: it takes approximately 1724 miliseconds to complete for 10000 elements (You can see this by running the script and checking inspector).
var start = new Date();
var n = 10000;
var iCount;
var option1;
var selectObject1 = document.getElementById('ifbchan');
for(iCount = 0; iCount < n; iCount++)
{
option1=document.createElement("option");
option1.text = "Out " + iCount;
option1.value=iCount;
try
{
selectObject1.add(option1, selectObject1.options[null]);
}
catch (e)
{
selectObject1.add(option1, null);
}
}
selectObject1.selectedIndex = 0;
var time = new Date() - start;
console.log(time);
I do not like a lot of this code (it is too many lines) so I will rewrite it in jquery.
var start = new Date();
var n = 10000;
for (var i = 0; i<n; i++){
$("#ifbchan").append("<option value="+i+">"+i+"</option>")
}
var time = new Date() - start;
console.log(time);
The next fiddle is here. Much less lines, and some time improvement. Now it is 1312 milliseconds. But it append new element in every loop.
The next fiddle get rid of this.
var start = new Date();
var n = 10000;
var html = '';
for (var i = 0; i<n; i++){
html += "<option value="+i+">"+i+"</option>";
}
$("#ifbchan").append(html);
var time = new Date() - start;
console.log(time);
Wow, now it is only 140 milliseconds.
for (var i = 0; i<n; i++){
select.append('<option value='+i+'>'+i+'</option>');
}
Beware, this doesn't work in IE. See this link -
Using innerHTML to Update a SELECT – Differences between IE and FF

populate select element based on json

How could I populate a second select element? I've figured out how to do the first one. But how could I do the same for the second depending on which "Make" is selected? I've tried to talk myself through it while taking small steps but I'm thinking this may be too advanced for me.
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"},{"name":"Spider","value":"22172"}]}';
var carobj = eval ("(" + cars + ")");
var select = document.getElementsByTagName('select')[0];
//print array elements out
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
select.options.add(new Option(d.name, i))
};
If I read your question right, you want to populate a second select with the models for the make in the first select. See below for a purely JS approach (with jsfiddle). If possible, I would recommend looking into jQuery, since I would prefer a jQuery solution.
http://jsfiddle.net/m5U8r/1/
var carobj;
window.onload = function () {
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"}, {"name":"Spider","value":"22172"}]}]}';
carobj = eval ("(" + cars + ")");
var makes = document.getElementById('make');
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
makes.options.add(new Option(d.name, i));
}
makes.onchange = getModels;
getModels();
}
// add models based on make
function getModels () {
var makes = document.getElementById('make');
var make = makes.options[makes.selectedIndex].text;
for (var i = 0; i < carobj.USED.length; i++) {
if (carobj.USED[i].name == make) {
var models = document.getElementById('model');
models.options.length = 0;
for (var j= 0; j < carobj.USED[i].models.length; j++) {
var model = carobj.USED[i].models[j];
models.options.add(new Option(model.name, j));
}
break;
}
}
}
I would also recommend looking into safer JSON parsing. There is a security risk in using eval if it runs on any user input. You could look into JSON.org and their json2.js. Or if you want to use jQuery: parseJSON. Below is the jQuery version:
jQuery.parseJSON(jsonString);
JSON parsing tips from: Safely turning a JSON string into an object.

How to simplify this javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to simplify this code?
What is the best way to simplify this for going from 1-19?
var backer1 = document.getElementById("backer-prediction-1").value;
var incentive1 = document.getElementById("incentive-cost-1").value;
var totalIncentive1 = parseInt(backer1,10) * parseInt(incentive1,10);
document.getElementById("incentive-total-1").value = totalIncentive1;
var backer2 = document.getElementById("backer-prediction-2").value;
var incentive2 = document.getElementById("incentive-cost-2").value;
var totalIncentive2 = parseInt(backer2,10) * parseInt(incentive2,10);
document.getElementById("incentive-total-2").value = totalIncentive2;
Last one I posted they gave me a "for" loop.
Still learning this stuff.. Very New, THANKS!!!
Just like the last question, use a for loop:
for(var i = 1; i < 20; i++){
var backer = document.getElementById("backer-prediction-"+i).value;
var incentive = document.getElementById("incentive-cost-"+i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-"+i).value = totalIncentive;
}
for (var i=1; i<=19; i++) {
var backer = document.getElementById("backer-prediction-" + i).value;
var incentive = document.getElementById("incentive-cost-" + i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-" + i).value = totalIncentive;
}
This untested code should be enough, unless you need access to the backer and incentive values for each one of the cases after the loop is completed.
Use Array in javascript
var backer=[],
incentive=[],
totalincentive=[];
for(var i=1;i<20;i++){
backer[i] = document.getElementById("backer-prediction-"+i).value;
incentive[i] = document.getElementById("incentive-cost-"+i).value;
totalIncentive[i] = parseInt(backer[i],10) * parseInt(incentive[1],10);
document.getElementById("incentive-total-"+i).value = totalIncentive[i];
}
So you can use them after ending for loop , like
backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]
If the value of backer and incentive is a number, I'd be tempted to do:
var get = document.getElementById;
var backer, incentive, totalIncentive = 0;
for(var i = 1; i < 20; i++) {
totalIncentive += get("backer-prediction-" + i).value * get("incentive-cost-" + i).value;
}
as the multiplication will implicitly convert numeric strings to numbers. But you really should validate that the content of those elements is a valid number before doing anything, even if using parseInt.

Categories