I want to retrieve a random row from the table of meals, how is the way to do that?
My code :
var transaction = db.transaction(["meals"], "readonly");
var store = transaction.objectStore("meals");
var index = store.index("time"); // to search in the field time type
range = IDBKeyRange.only(3); // 3 means it is a lunch
index.openCursor(range).onsuccess = function (e) {
var dt = event.target.result;
if (dt) {
var s = dt.value['fno1'];
}
};
Instead of advancing one row at a time until you hit your random result, what about using advance(n) to jump up a random set? Here is a complete example. It assumes two buttons to seed data and to call the random selection. I'm going to be blogging this Monday.
/* global $,document,indexedDB,console */
/**
* Returns a random integer between min and max
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(document).ready(function() {
var db;
var openRequest = indexedDB.open("randomidb",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
console.log("running onupgradeneeded");
if(!thisDB.objectStoreNames.contains("notes")) {
thisDB.createObjectStore("notes", {autoIncrement:true});
}
};
openRequest.onsuccess = function(e) {
console.log("running onsuccess");
db = e.target.result;
$("#seedButton").on("click", function() {
var store = db.transaction(["notes"],"readwrite").objectStore("notes");
for(var i=0; i<10; i++) {
var note = {
title:"Just a random note: "+getRandomInt(1,99999),
created:new Date()
};
var request = store.add(note);
request.onerror = function(e) {
console.log("Error",e.target.error.name);
//some type of error handler
};
request.onsuccess = function(e) {
console.log("Woot! Did it");
};
}
});
$("#randomButton").on("click", function() {
//success handler, could be passed in
var done = function(ob) {
console.log("Random result",ob);
};
//ok, first get the count
var store = db.transaction(["notes"],"readonly").objectStore("notes");
store.count().onsuccess = function(event) {
var total = event.target.result;
var needRandom = true;
console.log("ok, total is "+total);
store.openCursor().onsuccess = function(e) {
var cursor = e.target.result;
if(needRandom) {
var advance = getRandomInt(0, total-1);
console.log("going up "+advance);
if(advance > 0) {
needRandom = false;
cursor.advance(advance);
} else {
done(cursor);
}
} else {
done(cursor);
}
};
};
});
};
});
OK, I have developed this solution and it works just perfect to retrieve random row from table:
var transaction = db.transaction(["meals"], "readonly");
var store = transaction.objectStore("meals"); // name of table
var index = store.index("time"); // time is name of field and it is a number
range = IDBKeyRange.only(2); // query when time = 2
var y = 1;
var z = true;
var x = 0; // it will equal the random number
index.openCursor(range).onsuccess = function (e) {
var dt = event.target.result;
if (z) {
x = RandInt(1, dt.key); // get random number between 1 and count of rows
z = false; // to only make the above line one time only
}
if (dt) {
if (x == y) {
var s = dt.value['fno1'];
}
else
{ y += 1; dt.continue();}
}
};
Function to get the random number between two values :
function RandInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Related
my javascript isn't the best. I have some code here in the form of a calculator:
https://jsfiddle.net/yadL05aL/
my javascript:
// Get a list of your products and pop them into a dropdownlist
function GetProducts() {
var products = V12.getFinanceProducts();
var ddlProducts = document.getElementById('productsList');
for (var i = 0; i < products.length; i++) {
var newItem = new Option(products[i].name, products[i].productId);
ddlProducts.appendChild(newItem);
}
}
// Get details of repayments for the product selected
function CalculateRepayments() {
var productId = $('#productsList').val(); // selected product
var financeProduct = V12.getFinanceProduct(productId); // get the object
var cashPrice = $('#cashPrice').val();
var depositFactor = $('#deposit').val();
var deposit = cashPrice * (depositFactor / 100);
var payments = V12.calculate(financeProduct, cashPrice, deposit);
PopulateDescription(payments);
}
function UpdateLoanInfo() {
$('#cashPrice').val($('#cpRange').val());
$('#deposit').val($('#depRange').val());
CalculateRepayments();
}
// Show repayment plan details in the description
function PopulateDescription(payments) {
$('#lblFinalPayment').html('');
$('#lblDeposit').html('£' + payments.deposit);
$('#lblInitPayments').html('£' + payments.initialPayments);
$('#lblTotalRepayable').html('£' + payments.amountPayable);
$('#lblInterest').html(payments.apr + '%');
if (payments.initialPayments != payments.finalPayment && payments.finalPayment > 0) {
$('#lblMonths').html(payments.months - 1);
$('#lblFinalPayment').html(' and a final payment of £' + payments.finalPayment);
} else {
$('#lblMonths').html(payments.months);
}
}
// Firing this will loop through your V12 products and grab the product with the lowest
// possible monthly payments.
function GetLowestMonthlyPayments() {
var products = V12.getFinanceProducts();
var lowestMonthlyPayment = 0;
var lowestMonthlyPaymentProductId = 0;
for (var i = 0; i < products.length - 1; i++) {
var product = V12.getFinanceProduct(products[i].productId);
var cashPrice = $('#cashPrice').val();
var depositFactor = $('#deposit').val();
var deposit = cashPrice * (depositFactor / 100);
var payments = V12.calculate(product, cashPrice, deposit);
var monthlyPayment = payments.initialPayments;
if (parseFloat(lowestMonthlyPayment) > parseFloat(monthlyPayment) || lowestMonthlyPayment == 0) {
lowestMonthlyPayment = payments.initialPayments;
lowestMonthlyPaymentProductId = product.productId;
}
}
$("#productsList").val(lowestMonthlyPaymentProductId);
CalculateRepayments();
}
// Ready up our events
(function ($) {
GetProducts();
CalculateRepayments();
$('#productsList').on('change', function () {
CalculateRepayments();
});
$('#cpRange, #depRange').on("input", function () {
UpdateLoanInfo();
});
$('#lowestMonthlyPayments').click(function () {
GetLowestMonthlyPayments();
});
$('#cashPrice, #deposit').keyup(function () {
var cp = $('#cashPrice').val();
var dep = $('#deposit').val();
$('#cpRange').val(cp);
$('#depRange').val(dep);
CalculateRepayments();
});
//spinner//
$('<div class="quantity-nav"><div class="quantity-button quantity-up">+</div><div class="quantity-button quantity-down">-</div></div>').insertAfter('.quantity input');
$('.quantity').each(function() {
var spinner = jQuery(this),
input = spinner.find('input[type="number"]'),
btnUp = spinner.find('.quantity-up'),
btnDown = spinner.find('.quantity-down'),
min = input.attr('min'),
max = input.attr('max');
btnUp.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue >= max) {
var newVal = oldValue;
} else {
var newVal = oldValue + 100;
}
spinner.find("input").val(newVal);
spinner.find("#cpRange").val(cp);
spinner.find("#depRange").val(dep);
spinner.find("input, #cashPrice").trigger("change");
});
btnDown.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue <= min) {
var newVal = oldValue;
} else {
var newVal = oldValue - 100;
}
spinner.find("input").val(newVal);
spinner.find("input").trigger("change");
});
});
})(jQuery);
what I am trying to achieve is when you click on the plus and minus buttons in the cash price input, the bottom labels reflect the decrease or increment changes to the deposit / monthly repayments & APR.
Can anyone please point me in the right direction?
Kind regards
Robbie
Please help....Tried executing the below mentioned function but web console always shows
TypeError: xml.location.forecast[j] is undefined
I was able to print the values in alert but the code is not giving output to the browser because of this error. Tried initializing j in different locations and used different increment methods.How can i get pass this TypeError
Meteogram.prototype.parseYrData = function () {
var meteogram = this,xml = this.xml,pointStart;
if (!xml) {
return this.error();
}
var j;
$.each(xml.location.forecast, function (i,forecast) {
j= Number(i)+1;
var oldto = xml.location.forecast[j]["#attributes"].iso8601;
var mettemp=parseInt(xml.location.forecast[i]["#attributes"].temperature, 10);
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
from = from.replace(/-/g, '/').replace('T', ' ');
from = Date.parse(from);
to = to.replace(/-/g, '/').replace('T', ' ');
to = Date.parse(to);
if (to > pointStart + 4 * 24 * 36e5) {
return;
}
if (i === 0) {
meteogram.resolution = to - from;
}
meteogram.temperatures.push({
x: from,
y: mettemp,
to: to,
index: i
});
if (i === 0) {
pointStart = (from + to) / 2;
}
});
this.smoothLine(this.temperatures);
this.createChart();
};
You are trying to access the element after the last one. You can check if there is the element pointed by j before proceeding:
Meteogram.prototype.parseYrData = function () {
var meteogram = this,
xml = this.xml,
pointStart;
if (!xml) {
return this.error();
}
var i = 0;
var j;
$.each(xml.location.forecast, function (i, forecast) {
j = Number(i) + 1;
if (!xml.location.forecast[j]) return;
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
});
};
I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
});
I have a function to select a random number from 0 to 45 and then I show the div with the specific ID. It's working fine but it repeats a number.
Can anyone advise so it won't repeat numbers?
I call the function onclick like this
$(".skip").click(function () {
scared++;
$("#counter").html("My current count is: " + dared);
var d = 50;
/*$(".question").addClass("hideMe");
$(this).parents("div").next("div").removeClass("hideMe");*/
var r = Math.round(Math.random() * 44) + 1;
var newquestion = "q" + r;
$('.active').removeClass("active");
$("#" + newquestion).addClass("active");
if (scared > 44) {
$('.main').fadeOut('fast');
$('.logo').switchClass("logo", "share");
$('.progress').css("display", "none");
$('.share-game').css("display", "block");
$('.hero').css("right", "-240px");
$('#score-total').html(score + '');
} else {
}
$('.red-line').append('<div id="children' + (d++) + '" class="red"></div>');
return false;
});
You can see what i did.
var usedNumbers = [];
var randomNumbers = [];
$(function() {
//Getting 20 random numbers
for (i = 0; i < 20; i++) {
randomNumbers.push(getRandomNumber());
}
console.log(randomNumbers);
function getRandomNumber() {
var hasInArray = true;
do {
var r = Math.round(Math.random() * 44) + 1;
if (usedNumbers.indexOf(r) === -1) {
usedNumbers.push(r);
hasInArray = false;
return r;
}
} while (hasInArray === true);
}
});
Warning to not set the numbers of randomnumbers more then what you want to get, because that will cause an infinite loop!
Use an array to capture the used numbers and then check that array on each click, generating a new number if that one is found. It resets back to an empty array when it is full.
var savedNumbers = [];
function getRandom() {
if (savedNumbers.length === 45) {
savedNumbers = [];
}
var r = Math.round(Math.random() * 44) + 1;
if (savedNumbers.indexOf(r) > -1) {
getRandom();
} else {
savedNumbers.push(r);
return r;
}
}
DEMO
I'm trying to write a function that adds a new "row" that has an optional "cell" to an object. Here is my code:
var init = function() {
var num = 0;
var count = 0;
var SC = {}
var rowAdd = function() {
num = num + 1
var cellstate = false;
var objCount = count + 1
var rowObj = {
number: num,
cell: cellstate
}
return SC.rowObj;
}
var initialize = function() {
rowAdd();
}
initialize();
}
$(document).ready(function() {
init();
addRowBtn.click(function() {
rowAdd();
});
addCellBtn.click(function() {
SC.row1.cell = true;
});
});
This approach rewrites the row everytime i call rowAdd(). In the end I want a single object SC to contain every row, and each row should have a cell property. How can I do this?
Try this. You can just use num for objCount too and no need for cellState variable.
var init = function() {
var num = 0, SC = {}
var rowAdd = function() {
num = num + 1;
SC["row" + num] = {
number: num,
cell: false
}
return SC;
}
}
How about making SC an array and pushing the new row onto the array:
var SC = [];
var rowAdd = function() {
num = num + 1
var cellstate = false;
var objCount = count + 1;
var rowObj = "row" + objCount;
var rowObj = {
number: num,
cell: cellstate
}
return SC.push(rowObj);
}
You'll want to have an array object on SC to hold your rows.
var SC = { rows: [] };
And then add to it
SC.rows.push(rowObj);
To access
SC.rows[index]