i got javaScript array hold elements records with unique elementIndex in it now what I have to add single or multiple components in same javaScript array for that particular element (same elementIdex).
this array can have as many elements as required and each element may have one or multiple components associated to that element.
I have managed to do first part, how i do second part ... that is add components records associated to single element.
note element and component are in separate javaScript function but i have global array
this is what i want to achieve (may be JSON)
QualificationElemenetsAndComponents[0] = {
Element [
ElementIndex : "",
ElementMarkingSchemeTitle : "",
ElementAvailableMark: "",
ElementPassMark: "",
ElementDistinctionMark: "",
Component[0]= [
componentIndex="",
componentMark =""
],
Component[1]= [
componentIndex="",
componentMark =""
],
Component[2]= [
componentIndex="",
componentMark =""
],
}
global array
var selectedComponentList = [];
var selectElementList = [];
element
$("#ElementTable").on("click", ".k1-grid-confirm", function () {
var E_RecordId = $(this).data("id");
var E_MarkingSchemeTitle = $("#" + E_RecordId + "_EMST").val();
var E_AvailableMark = $("#" + E_RecordId + "_AM").val();
var E_PassMark = $("#" + E_RecordId + "_PM").val();
var E_MeritMark = $("#" + E_RecordId + "_MM").val();
var E_DistinctionMark = $("#" + E_RecordId + "_DM").val();
alert("elementRecordId " + E_RecordId + " E_MarkingSchemeTitle " + E_MarkingSchemeTitle + " E_AvailableMark " + E_AvailableMark + " E_PassMark " + E_PassMark + " E_MeritMark " + E_MeritMark + " E_DistinctionMark " + E_DistinctionMark);
//add data to array//
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });
}
});
Component
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMark = $("#" + recordId + "_CM").val();
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
//push array to Selected Element
?????????????????????????????????????
}
});
Many thanks
Define a function to refresh the global list:
// Elements
selectElementList.push({...});
refreshGlobalList();
// Components
selectedComponentList.push({...});
refreshGlobalList();
And the function:
var globalList = [];
function refreshGlobalList() {
globalList = selectElementList.concat(selectedComponentList);
}
arrayNum.push.apply(arrayNum, arrayValuTwo);
arrayNum.push.apply(arrayNum, arrayValuThree);
you can try this or you can try this
arrayNumber.push.apply(arrayNumber, arrayValueTwo.concat(arrayValueThree));
Related
$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>
For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}
i have a json object that has item type and id, i need to create new object
var data = {
"items":[
{"type":"generator","id":"item_1","x":200,"y":200},
{"type":"battery","id":"item_2","x":50,"y":300},
{"type":"generator","id":"item_3","x":200,"y":280},
{"type":"battery","id":"item_4","x":100,"y":400}
]
};
and i need to run for each item in items
jQuery.each(data.items, function(index,value) {
eval("var " + value.id + " = new " + value.type + "(" + (index + 1) + ");");
eval(value.id + ".id = '" + value.id + "';");
eval(value.id + ".draw(" + value.x + "," + value.y + ");")
});
this is not a good practice, but what else can i do?
i need then to have the control on the items
something like
item_1.moveto(300,700);
but i always get item_1 is undefind
You can create a factory method which allows to generate concrete types out of an abstract data structure:
var createItem = (function () {
var types = {};
function createItem(index, data) {
data = data || {};
var ctor = types[data.type], item;
if (!ctor) throw new Error("'" + data.type + "' is not a registered item type.");
item = new ctor(index);
item.id = data.id;
return item;
}
createItem.registerType = function (type, ctor) {
types[type] = ctor;
};
return createItem;
})();
Then register item types to the factory:
function Generator(index) {/*...*/}
createItem.registerType('generator', Generator);
And finally create an object map to lookup your items by id (you could use a specialized object like ItemsMap instead of a plain object), loop through your items and add them to the map.
var itemsMap = {};
data.items.forEach(function (itemData, i) {
var item = itemsMap[itemData.id] = createItem(i + 1, itemData);
//you can also draw them at this point
item.draw(itemData.x, itemData.y);
});
You can now lookup objects by id like:
var item1 = itemsMap['item_1'];
var objects = {};
objects[value.id] = new window[value.type](index + 1);
Here is a sample of my problem and below is the same code
HTML
<button id='preview_btn'>Add</button>
<table id="point_tbl">
</table>
JavaScript
var pointList = [];
function deletePoint(id) {
console.log(id); // should be string but turns out to be the tr element
for (var i = 0; i < pointList.length; i++) {
if (pointList[i].id == id) {
pointList.splice(i, 1);
document.getElementById(id).remove();
document.getElementById(id + "item").remove();
}
}
}
function getTemplate(obj) {
var id = obj.id + "item";
var aa = obj.id;
var row = "<tr id = '" + id + "'><td>" + obj.sn + "</td><td>" + obj.x + "</td><td>" + obj.y + "</td><td>" + obj.tx + "</td><td>" + obj.ty + "</td><td>" + obj.lbl + "</td><td><button class='del_point' onclick = 'deletePoint("+id+");'>Delete</button></td></tr>";
return row;
}
document.getElementById("preview_btn").onclick = function(event) {
var id = getUniqueId();
var obj = {sn: pointList.length, x: 10, y: 10, tx: "0.5", ty: "0.5", lbl: "", id: id};
$('#point_tbl').append(getTemplate(obj));
pointList.push(obj);
}
function getUniqueId() {
if (!getUniqueId.idList) {
getUniqueId.idList = [];
}
var id = "uniqueID" + Math.round(Math.random() * 1000 + 1);
if (getUniqueId.idList.indexOf(id) != -1) {
return getUniqueId();
} else {
getUniqueId.idList.push(id);
}
return id;
}
When the Add button is clicked a new row is added with a button.
On this newly added button the deletePoint function is bind using the getTemplate function. The deletePoint function accepts the id of the row (tr) created by getTemplate function.
I am logging the the passed parameter in the deletePoint function. I was expecting this to be the id(basically a string) of the row but it turns out to be the whole tr element.
Not able to rectify the problem, please help.
What happens is that the generated code in the event handler is
deletePoint(someId)
instead of being
deletePoint("someId")
As most browsers create a variable in global scope for all elements having an id (the name of the variable being the id), you pass the element, not the string (in some browsers you would pass undefined).
Immediate fix : Change
onclick = 'deletePoint("+id+");'
to
onclick = 'deletePoint(\""+id+"\");'
Better : don't inline JS code in HTML to avoid those problems. For example give an id and data-attribute to your cell and later bind as you do with other elements.
You can change your delete function to fix problem
function deletePoint(id) {
id.remove();
}
function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.