trying to add multiple similar objects to another object - javascript

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]

Related

how to find index of array using substring value in javascript and replace with a new string?

I am getting string -
["1-2","10-4","2-3","3-1","4-4","5-2","6-4","7-3","8-1","9-2"]
as output from GetOption function where event - QuestionID & event1 -OptionID
Project-Online Examination System
var getValue;
var getName = new Array();
var temp = new Array();
function GetOption(event, event1) {
debugger;
if (temp.includes(event)) {
var x = getName.indexOf(event);
getName.splice(x - 1, 1);
getName.includes(event);
}
this.event1 = event1;
temp.push(event);
var getValue = event + "-" + event1;
if (getValue == "undefined-undefined") {
getName.push("");
} else {
getName.push(getValue);
getName.sort();
alert(getName);
}
$("#resultHidden").val(getName);
}
var items = ["1-2","10-4","2-3","3-1","4-4","5-2","6-4","7-3","8-1","9-2"];
var searchItems = "1-2";
var newItems = "2-1";
for (var i = 0; i < items.length; i++) {
if (items[i].startsWith(searchItems)) {
items[i] = newItems;
}
}

Increment value in function

I want to increment my i value to save different value to local storage. But i always = 0, what can I do to change this behavior?
(function() {
var i = 0;
var storage = new Storage();
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set("task-"+i, ticket);
i++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
Declare the var i = 0 outside of the function. Right now it is being reset to 0 every time to function is run.

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

update list property in listTicker function every X seconds

I am attempting to create a ticker that fades in and out the objects in an array using the jQuery fadeIn/fadeOut function. I referenced someone else's code and was able to get it working for the most part. What I would like to do now is get the list property of listTicker to update every X number of seconds and move to the next array. I assume I must use a for loop somehow but I just cant seem to figure out how to implement it.
Below is what I was able to get working:
var listTicker = function(options) {
var defaults = {
list: [],
startIndex:0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function(index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value= options.list[index];
options.trickerPanel.fadeOut(function() {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function() {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
};
var textlist = new Array("Saab", "Volvo", "BMW");
var textlist2 = new Array("Dell", "HP", "Toshiba");
var textlist3 = new Array("John", "Dave", "Greg");
var currentlist = new Array(textlist, textlist2, textlist3);
$(function() {
listTicker({
list: currentlist[0] ,
startIndex:0,
trickerPanel: $('#expression'),
interval: 3 * 1000,
});
});
Not 100% happy with the organization/separation of this code, but it achieves the objective:
http://jsfiddle.net/49Y8s/
options.trickerPanel.fadeOut(function() {
$(this).html(value).fadeIn();
var nextItemIndex = (index+1) < currentList.length ? (index+1) : 0;
var nextListIndex = (function(){
var val = listIndex;
if(nextItemIndex==0){
val = listIndex+1;
}
if(val >= options.lists.length){
val = 0;
}
return val;
})();
setTimeout(function() {
listTickerInner(nextListIndex,nextItemIndex);
}, options.interval);
});

javascript function for calculating

I meet a trouble with a function. actually I need to make this function to perform a calculation on some text fields. When I worked on a single line no problems. But recently, someone asked to make a table with multiple lines (one line can be added dynamically) so, I do the following function so that it can not only duplicate line but id change all the fields concerned, so I add class to these fields. therefore I proceed as follows:
function clone(line) {
newLine = line.cloneNode(true);
line.parentNode.appendChild(newLine);
var tab = document.getElementsByClassName('libelle_debours')
var i = -1;
while (tab[++i]) {
tab[i].setAttribute("id", "_" + i);
};
var cab = document.getElementsByClassName('ht_no_tva')
var j = -1;
while (cab[++j]) {
cab[j].setAttribute("id", "_" + j);
};
var dab = document.getElementsByClassName('ht_tva')
var k = -1;
while (dab[++k]) {
dab[k].setAttribute("id", "_" + k);
};
var eab = document.getElementsByClassName('taux')
var l = -1;
while (eab[++l]) {
eab[l].setAttribute("id", "_" + l);
};
var fab = document.getElementsByClassName('tva')
var m = -1;
while (fab[++m]) {
fab[m].setAttribute("id", "_" + m);
};
}
function delRow() {
var current = window.event.srcElement;
//here we will delete the line
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
The problem in fact is the second function that is used to make the calculation:
function calcdebours() {
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva = Math.round((((ht_tva) * (taux)) / 100) * 100) / 100;;
if (taux == '') {
taux = 0;
}
if (ht_no_tva == '') {
ht_no_tva = 0;
}
if (ht_tva == '') {
ht_tva = 0;
}
document.getElementById('debours_montant_tva').value = tva;
document.getElementById('debours_montant_ttc').value = (tva) + parseFloat(ht_tva) + parseFloat(ht_no_tva)
}
function
montant_debours() {
var ttc = document.getElementById('debours_montant_ttc').value;
var ttc2 = document.getElementById('debours_montant_ttc2').value;
if (ttc == '') {
var ttc = 0;
} else {
var ttc = document.getElementById('debours_montant_ttc').value;
}
if (ttc2 == '') {
var ttc2 = 0;
} else {
var ttc2 = document.getElementById('debours_montant_ttc2').value;
}
tx = parseFloat(ttc) + parseFloat(ttc2);
document.getElementById('ttc_cheque').value = Math.round(tx * 100) / 100;
}
As Id are not the same, do I have to create as many functions
there are lines?
Is it possible to fit a single function to process each line?
If so can you tell me how?
If I'm not mistaken you can use for loop and append increment to the end of element's id. Like this:
trs = document.getElementById('container Id').getElementsByTagName('tr');
For (var i = 1, i <= trs.length; i++)
{
var el = document.getElementById('debours_montant_ttc' + i);
}

Categories

Resources