I have:
var cboxHTMLString = "<input type='checkbox' class='custom-control-input'"
+ "id='customCheck1' name=${" + check_name + "}>"
+ "<label class='custom-control-label' for='customCheck1'>"
+ "</label>";
var div = document.createElement('div');
div.setAttribute("class", "custom-control custom-checkbox");
var checkbox_div = createElementFromHTML(cboxHTMLString, div);
The function being called is:
function createElementFromHTML(htmlString, element){
element.innerHTML = htmlString.trim();
return element; //.childNodes;
};
I then fill an object with the new key-value and other key-values I received from php/mysql:
var d_dict = {Select: checkbox_div};
//iterate disease_dict and add k,v to d_dict
for(let key in disease_dict) {
var new_key = key;
var new_val = disease_dict[key];
d_dict[new_key] = new_val;
}
Then I fill my table cells:
for(let key in d_dict){
let cell = row.insertCell(-1);
if(key==='Select'){
var checkbox_html = d_dict[key];
cell.innerHTML = checkbox_html;
console.log(cell);
}
else{
let val = d_dict[key];
let newText = document.createTextNode(val);
cell.appendChild(newText);
console.log(cell);
}
}
But it shows the text instead of the checkbox.
Edit:
I did
for(k in checkbox_html){
console.log(checkbox_html[k]);
}
and it showed me a bunch of integers:
What does that mean?
Your createElementFromHTML() function returns a DOM element object, not a string of HTML:
var checkbox_div = createElementFromHTML(cboxHTMLString, div);
Because it is a DOM element, you must use the .appendChild() method to append it to the cell:
if(key==='Select'){
var checkbox_html = d_dict[key];
cell.appendChild( checkbox_html );
}
Related
I like to add an input field to my list element for the timer im working on.
The problem is that it can read the function but doesnt display the object.
//Input Element Object
function inputElement() {
this.input = document.createElement("input");
this.input.id = "Timer " + count
this.input.type = "number";
this.input.max = 10;
this.input.min = 01;
}
function LI(id) {
this.li = document.createElement("li");
this.li.id = id;
this.li.id += count;
this.input = new inputElement();
this.li.innerHTML += this.input + ` set Timer`;
this.setting = document.getElementById("Version3");
this.setting.append(this.li);
}
I've a function in javascript which creates table of properties dynamically:
// update table
PropertyWindow.prototype._update = function (text) {
if (text === void 0) { text = "<no properties to display>"; }
this._propertyWindow.html(text);
};
PropertyWindow.prototype._onModelStructureReady = function () {
this._assemblyTreeReadyOccurred = true;
this._update();
};
// create row for property table
PropertyWindow.prototype._createRow = function (key, property, classStr) {
if (classStr === void 0) { classStr = ""; }
var tableRow = document.createElement("tr");
tableRow.id = "propertyTableRow_" + key + "_" + property;
if (classStr.length > 0) {
tableRow.classList.add(classStr);
}
var keyDiv = document.createElement("td");
keyDiv.id = "propertyDiv_" + key;
keyDiv.innerHTML = key;
var propertyDiv = document.createElement("td");
propertyDiv.id = "propertyDiv_" + property;
propertyDiv.innerHTML = property;
tableRow.appendChild(keyDiv);
tableRow.appendChild(propertyDiv);
return tableRow;
};
I want to take that generated table into json/xml and save this into a new file, how would I do this?
You can basically loop through the generated table like below and convert it into json with the following code
var myRows = [];
var $headers = $("th");
//your table path here inside the selector
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($headers[cellIndex]).html()] = $(this).html();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));
Possible duplicate
I have a server that collects data from 10 sources and constantly pushes JSON data to a webpage. The page uses JSON.Parse to get it into an object widgetData. The object widgetData has 10 properties that I want to display in the "widget".
So, the server is pushing WidgetData1, WidgetData2, etc..
For each widgetData, I want to create/instantiate a new widget and show the data. If widget1 exists, then update the widget. Also, the widgets should be sorted by some text property(e.g. widgetdata.name).
Here's what I've done so far, but the it doesn't seem that robust:
<script type="text/javascript">
var properties = ["MachineID", "p1","p2,"p3","p4"];
var currentWidget;
function CreateBlock(widgetData)
{
var widgetID = widgetData.MachineID.replace(/ /g,"_");
var myWidget = document.getElementById('widget-' + widgetID);
if (myWidget == null)
{
CreateCard(widgetID);
}
var currentDate = new Date();
var day = currentDate.getDay();
var month = currentDate.getMonth(); //Be careful! January is 0 not 1
var year = currentDate.getFullYear();
var hour = currentDate.getHours();
var min = currentDate.getMinutes();
var sec = currentDate.getSeconds();
var dateString = year + "-" + ZeroPad(month+1,2) + "-" + day + " " + ZeroPad(hour,2) + ":" + ZeroPad(min,2) + ":" + ZeroPad(sec,2);
var data;
for (let i = 0; i < properties.length; i++)
{
data = widgetData[properties[i]];
AddDataElement(widgetID,properties[i],data);
}
AddDataElement(widgetID,"Timestamp",dateString);
}
//create the card
function CreateCard(cardID)
{
var parent
var newdiv
var cardElement = document.createElement("div");
cardElement.className = "card";
cardElement.id = "widget-" + cardID;
cardElement.style = "height:500px;";
parent=cardElement;
newdiv = document.createElement("div");
newdiv.className = "card-header";
parent.appendChild(newdiv);
//parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-body";
newdiv.id = "cardbody";
parent.appendChild(newdiv);
parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-title";
newdiv.id = "title";
newdiv.textContent = "title";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
newdiv.className = "card-sub-title";
newdiv.id = "subtitle";
newdiv.textContent = "subtitle";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
parent.appendChild(newdiv);
//last add to the parent div
var parent = document.getElementById("Cards");
parent.appendChild(cardElement);
}
//Add a data element
function AddDataElement(machineID, title, value)
{
var cardElement = document.getElementById("widget-" + machineID);
var cardElementBody = findChild("widget-" + machineID, "cardbody");
var dataElement = findChild2(cardElementBody, title);
if (dataElement == null)
{
dataElement = document.createElement("div");
dataElement.id = title;
dataElement.className = "card-item";
}
dataElement.innerText = title + ": " + value;
cardElementBody.appendChild(dataElement);
}
function CreateElement(parentDivObject, childName)
{
var dataElement = document.createElement('DIV');
dataElement.id = childName;
dataElement.textContent = childName;
parentDivObject.appendChild(dataElement);
}
function findChild(idOfElement, idOfChild)
{
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
function findChild2(parentElement, idOfChild)
{
//let element = document.getElementById(idOfElement);
return parentElement.querySelector('[id=' + idOfChild + ']');
}
function ZeroPad(num, places)
{
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
</script>
<script type="text/javascript">
var widgetList = new Set(); //hold list of widgets
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/');
//when data is comming from the server, this method is called
//ws.onmessage = function (evt) {
// inc.innerHTML += evt.data + '<br/>';
//};
ws.onmessage = function (evt)
{
var machineStatus = JSON.parse(evt.data);
if (!widgetList.has(machineStatus.MachineID))
{
widgetList.add(machineStatus.MachineID)
}
CreateBlock(machineStatus)
}
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
What is an alternative, proper way, or best practice to accomplish this?
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
The function above gets an input value from a field in a set of rows using jQuery .val()
var table = document.getElementById('DYN_6000-LISTSAPLMEGUI-tab');
var t = table.rows.length;
//getting current blank cell ID and upping the blank cell ID to the new last cell
var new_cell_id = table.rows.item(t-1).id;
var old_cell_id = "DYN_6000-LISTSAPLMEGUI-key-" + t;
table.rows.item(t - 1).id = old_cell_id;
table.rows.item(t - 1).onmouseover = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onmouseout = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onclick = function () { showItemDetailDropDown_click(old_cell_id); };
//create new row and table
var drop_down_height = document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height;
document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height = (parseInt(drop_down_height.replace("px", "")) + 18) + "px";
var new_row = table.insertRow(t-1);
var new_cell = new_row.insertCell(0);
new_row.insertCell(1);
//set new row and cell properties
new_row.id = new_cell_id;
new_row.classList.add('urNoUserSelect');
new_row.style.width = "100%";
new_row.style.height = "18px";
new_row.onmouseover = function () { showItemDetailDropDown_hover(new_cell_id); };
new_row.onmouseout = function () {showItemDetailDropDown_hover(new_cell_id); };
new_row.onclick = function () {showItemDetailDropDown_click(new_cell_id);};
new_cell.classList.add('urIlb2I');
new_cell.classList.add('urColorTxtStandard');
var new_item = t;
new_cell.innerHTML = "[ " + new_item + " ]";
var zyx = "grid#21.125#" + row + ",2#if";
document.getElementById(zyx).value = new_item;
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = new_cell.innerHTML;
checkButton('keyboard');
This JS function is part of an if else statement that checks if there is a new value in each row and adds a sequential number to a dropdown item menu below the table. My question is: How do I append or concatenate the first value (description) into the dropdown menu after the number? For example,
[ 1 ] descriptionInput (the value)
Everything works I just don't know how to pass the jQuery function back to JS or append each value.
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(inputbox.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
This will basically make a list when you hover over a certain string. The list will be based on the localstorage and make an inputbox for each point of that list.
The problem is the adding of eventlisteners. For some reason it always returns an empty value when the event is triggered of that inputbox.
function changeAmountProd(inputboxId) {
var products = JSON.parse(localStorage["products"]);
value = document.getElementById(inputboxId).value;
if(value < 1) {
return;
}
products[i].amount = value;
localStorage["products"] = JSON.stringify(products);
makeUL();
}
The problem is with the callback of your change event. You're referring to the changed element using the inputbox variable (that is available through the closure) but by the time your callback is invoked, inputbox will always point to the last generated element.
Try this instead:
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
See addEventListener
Try this:
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}