java script auto generate random string - javascript

I want the random string result(output) to display inside the text box so I can saved the value into my database.
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
output.innerHTML = generator.generate();
}, false);
});
})();
<p><button id="generate">Generate</button></p>
<p><code id="output"></code></p>
NOTE
Any idea on how to fix this? So when every time I click generate button the result will come out in a text box then save the value to my database.

(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
$("#output").val(generator.generate());
}, false);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><button id="generate">Generate</button></p>
<input type="" id="output" name="">

Simply you can replace code tag by input tag
<p><input id="output" type="text" value="" /></p>
and replace output.innerHTML to be
output.value= generator.generate();
Hope that's help

Related

getting the incremental input spinner + & - to update label text fields

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

Multiplying variables and showing result in a box

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;
}
});

How can I assign Id attribute to all the children of a contenteditable div on keyup?

I tried the following:
HTML:
<div contenteditable="true" id="editable"></div>
JS:
$('#editable').keyup(function() {
addID();
});
function addID()
{
$('#editable *').each(function() {
var t = GenerateID();
$(this).attr('id','id-' + t);
});
}
function GenerateID()
{
var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
var alphabet = '',
genID = '';
while(genID.length < 5)
{
alphabet = str.charAt(Math.floor(Math.random() * str.length));
genID += alphabet;
}
return genID;
}
But on every keyup it keeps on changing the ID.
How can I just set the id once for all the elements while typing, and still keep it unique throughout the div ?
JSFiddle
LAST UPDATE:
Now I checked the code in your fiddle and I'm sure it works. The checking for uniqueness can probably be made into a function, but i'll leave that to you:
$('#editable').on( 'keyup', addID );
var count = 0; // this will absolutely ensure that ID will be unique
function addID(){
var previousIDs = [];
$('#editable *').each(function() {
count++;
var thisID = $(this).attr( 'id' );
// let's check if we have duplicates:
var index = 0, len = previousIDs.length, isDuplicate = false;
for( index = 0; index < len; index++ ){
if ( thisID === previousIDs[index] ) {
isDuplicate = true;
break;
}
}
// now change the ID if needed:
if ( isDuplicate || ! thisID ){
var t = GenerateID();
var newID = 'id-' + t + '-' + count;
$(this).attr('id', newID);
previousIDs.push( newID );
}else{
previousIDs.push( thisID );
}
});
}
Working Fiddle
Try this:
$('#editable').keyup(addID);
function addID() {
$('#editable *').each(function () {
var t = GenerateID();
var elem = $(this);
var attr = elem.attr('id');
if (!attr) {
elem.attr('id', 'id-' + t);
}
});
}
/**
* #return {string}
*/
function GenerateID() {
var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
var alphabet = '',
genID = '';
while (genID.length < 5) {
alphabet = str.charAt(Math.floor(Math.random() * str.length));
genID += alphabet;
}
return genID;
}
Also consider that your random string generator may generate same string again.
Replace your code with following :
$('#editable *').each(function() {
if(!$(this).hasClass("idgenerated")){
console.log( $(this).attr('id') );
var t = GenerateID();
$(this).attr('id','id-' + t);
$(this).addClass("idgenerated");
console.log($(this).prop("tagName") + ' = ' + t);
}
});
Working fiddle

ExtJS 4 DatePicker. Coloring cells

I need help, I am trying to be able to apply different colors to the cells of an Extjs4 DatePicker component, I would like to say for example, if a specific day has uncomplete tasks mark that day as red.
Thanks in advance.
I already found a way to apply different colors to specific cells of an Extjs 4 DatePicker, I created a new component that extends form DatePicker and adds the cell coloring functionality.
I will copy the code here as I dont konw how to attach a file here :P
Ext.define('Framework.ux.form.EnhancedDatePicker', {
extend: 'Ext.picker.Date',
alias: 'widget.enhanceddatepicker',
yearMonthDictionary: {},
selectedCell: undefined,
fullUpdate: function(argDate){
this.callParent(arguments);
this.storeOriginalYearMonthClassNames();
this.addCurrentYearMonthClasses();
this.addSelectedCellClass();
},
storeOriginalYearMonthClassNames: function(){
var tmpCells = this.cells.elements;
for(var tmpIndex=0; tmpIndex < this.numDays;tmpIndex++) {
var tmpCell = tmpCells[tmpIndex];
var tmpCellDate = new Date(tmpCell.title);
var tmpClassName = tmpCell.className;
if( this.isCellSelected(tmpCell) ){
this.selectedCell = tmpCell;
tmpClassName = tmpCell.className.replace("x-datepicker-selected","");
}
this.storeYearMonthClassName(tmpCellDate,'originalClassName',tmpClassName);
}
},
isCellSelected: function(argCell){
if( Ext.isEmpty(argCell) ){
return false;
}
if( argCell.className.indexOf('x-datepicker-selected') >= 0 ){
return true;
}
return false;
},
storeYearMonthClassName: function(argDate,argField,argClassName){
if( Ext.isEmpty(argDate) || Ext.isEmpty(argField) ){
return;
}
var tmpMonthYearKey = argDate.getFullYear() + "-" + argDate.getMonth();
var tmpYearMonthValues = this.yearMonthDictionary[tmpMonthYearKey];
if( Ext.isEmpty(tmpYearMonthValues) ){
tmpYearMonthValues = {};
}
var tmpValue = tmpYearMonthValues[argDate.getDate()];
if( Ext.isEmpty(tmpValue) ){
tmpValue = {};
}
tmpValue[argField] = argClassName;
tmpYearMonthValues[argDate.getDate()] = tmpValue;
this.yearMonthDictionary[tmpMonthYearKey] = tmpYearMonthValues;
},
setDateClass: function(argDate,argClass){
if( Ext.isEmpty(argDate) ){
return;
}
var tmpCurrentDate = this.getValue();
var tmpCurrentMonthYearKey = tmpCurrentDate.getFullYear() + "-" + tmpCurrentDate.getMonth();
var tmpYearMonthKey = argDate.getFullYear() + "-" + argDate.getMonth();
this.addDateAndClassToDictionary(argDate,argClass);
this.addCurrentYearMonthClasses();
},
addDateAndClassToDictionary: function(argDate,argClass){
if( Ext.isEmpty(argDate) ){
return;
}
this.storeYearMonthClassName(argDate,'newClassName',argClass);
},
addCurrentYearMonthClasses: function(){
var tmpCells = this.cells.elements;
for(var tmpIndex=0; tmpIndex < this.numDays;tmpIndex++) {
var tmpCell = tmpCells[tmpIndex];
var tmpCellDate = new Date(tmpCell.title);
var tmpValue = this.getYearMonthValueByDate(tmpCellDate);
if( tmpValue.newClassName === null || tmpValue.newClassName === undefined ){
continue;
}
var tmpNewClassName = tmpValue.originalClassName + " " + tmpValue.newClassName;
if( tmpNewClassName !== tmpCell.className ){
tmpCell.className = tmpNewClassName;
}
}
},
getYearMonthValueByDate: function(argDate){
if( Ext.isEmpty(argDate) ){
return;
}
var tmpMonthYearKey = argDate.getFullYear() + "-" + argDate.getMonth();
var tmpYearMonthValues = this.yearMonthDictionary[tmpMonthYearKey];
if( Ext.isEmpty(tmpYearMonthValues) ){
return null;
}
return tmpYearMonthValues[argDate.getDate()];
},
addSelectedCellClass: function(){
if( this.selectedCell.className.indexOf('x-datepicker-selected') >= 0 ){
return;
}
this.selectedCell.className = this.selectedCell.className + " x-datepicker-selected";
}
});
This is an example on how to use the component:
var tmpDatePicker = this.down('datepicker[itemId=datePickerTest]');
var tmpDate = new Date(2013,4,2);
tmpDatePicker.setDateClass(tmpDate,"cell-red");
With those code lines we are telling the component to apply the class 'cell-red' to the cell corresponding to the date '2013-4-2'.
I hope this can be useful for people that was trying to accomplish this in Extjs 4.

trying to add multiple similar objects to another object

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]

Categories

Resources