The div tags are created inside this const and I have used a delete function to delete items from order page. I want to update prices after deletion and updating in text displaying totalprice.
total_price = total_price + parseInt(item.prisinklmoms);
// Create a row for the item in view
const order_item = document.createElement('div');
order_item.className = `ordered_item`;
order_item.innerHTML = `<div class="product-name">${item.namn}</div>
<div class="product-percentage">${item.alkoholhalt}</div>
<div class="product-price">${item.prisinklmoms}</div>
<button id="div-button" onclick="delOrderlist(this)">Del</button>`;
orderContainer.appendChild(order_item);
Related
<script>
//<body>
//<div class="prod"></div>
//<div class="details"></div>
//</body>
const product=document.querySelector(".prod");
var ourRequest=new XMLHttpRequest();
ourRequest.open('GET','http://inec.sg/assignment/retrieve_records.php');
ourRequest.onload=function(){
var data=JSON.parse(ourRequest.responseText);
renderHTML(data);
};
ourRequest.send();
function renderHTML(data){
for(var i=0;i<data.songs.length;i++){
product.innerHTML+=`
<div><img src="${data.songs[i].image}" height="200px"></div>
<div><h2>${data.songs[i].name}</h2></div>
<div><h2>$${data.songs[i].price}</h2></div>
<button id="">Details</button>
`;
}
}
//how do i display prod details when click on button? Able to hide the prod listing div, show the details in details div?
// details eg. data.songs.image, data.songs.brand, data.songs.style, data.songs.discount, data.songs.price
</script>
How do I display prod details when click on button? Able to hide the product listing div, show the details in details div?
Show these in details:
data.songs.image, data.songs.brand, data.songs.style, data.songs.discount, data.songs.price
This is what I came up with:
<button class="load">Load List</button>
<button class="hide">Hide List</button>
<div class="prod"></div>
<div class="details"></div>
<script>
const product = document.querySelector(".prod");
const details = document.querySelector(".details");
const loadBtn = document.querySelector(".load");
const hideBtn = document.querySelector(".hide");
loadBtn.addEventListener("click", () => { // on click of load button
// send request to get data
var ourRequest = new XMLHttpRequest();
ourRequest.open(
'GET',
'http://inec.sg/assignment/retrieve_records.php'
);
ourRequest.onload = function () {
var data = JSON.parse(ourRequest.responseText);
renderHTML(data);
};
ourRequest.send();
function renderHTML(data) {
product.innerHTML = ""; // empty product element
for (var i = 0; i < data.songs.length; i++) {
product.innerHTML += `
<div><img src="${data.songs[i].image}" height="200px"></div>
<div><h2>${data.songs[i].name}</h2></div>
<div><h2>$${data.songs[i].price}</h2></div>
<button data-index="${i}" class="detailsBtn">Details</button>
`; // data-index represents the index of the item in the songs array
}
let detailsBtns = document.querySelectorAll(".detailsBtn"); // get button element(s) previously created
for (var i = 0; i < detailsBtns.length; i++) {
let detailsBtn = detailsBtns[i];
detailsBtn.addEventListener("click", () => { // add on click event for individual details btn
// load details
let index = detailsBtn.dataset.index; // get index of song item
let song = data.songs[index];
details.innerHTML = `<h2>${song.image}</h2><h2>${song.brand}</h2><h2>${song.style}</h2><h2>${song.discount}</h2><h2>${song.price}</h2>`;
});
}
}
});
hideBtn.addEventListener("click", () => { // hide details when hide details button is clicked
product.innerHTML = ""; // empty product element
details.innerHTML = ""; // empty details element
});
</script>
First I declared and assigned common elements like product, details, hideBtn, and loadBtn.
I used the EventTarget.addEventListener() function to bind click events to loadBtn, hideBtn, and detailsBtn .
I used arrow functions for the callback functions of the events, but ES5 functions could certainly be used.
I used the HTMLElement.dataset attribute to link a song index to each product, so I can link the HTML of the product item(s) to their corresponding JS event functionality.
There are many other ways this could be done, but this is how I solved the problem.
How do I create a dynamic dependent dropdown list in Google AppsScript? What I want to achieve is, when I choose PH in order type, the product selection dropdown should have ['PH-Test Product 1', 'PH-Test Product 2', 'PH-Test Product 3'] options. And when I choose EC it should have ['EC-Test Product 1', 'EC-Test Product 2', 'EC-Test Product 3'].
Here's my code-
form.html
<head>
<base target="_top">
<?!= include('css_script'); ?>
</head>
<body>
<div class="container">
<div class = "row">
<h1>A Sample Form</h1>
</div>
<div id="productsection"></div>
<div class = "row">
<button id="addproduct">Add Product</button>
</div> <!-- end of row -->
</div>
<?!= include('js_script'); ?>
</body>
js_script.html
<script>
let counter = 0;
const orderTypeList = ["PH", "EC"];
const optionListPH = ["PH-Test Product 1", "PH-Test Product 2", "PH-Test Product 3"];
const optionListEC = ["EC-Test Product 1", "EC-Test Product 2", "EC-Test Product 3"];
document.getElementById("addproduct").addEventListener("click", addInputField);
function addInputField(){
counter++;
// creates a new div of class row
const newDivElem = createElementTemplate('div', `row${counter}`, 'row');
// creates a new select tag for order type dropdown
const newOrderTypeSelectElem = createElementTemplate('select', `ordertype${counter}`);
// function that populates the dropdown for products and is inserted to the above "ordertypeX" select tag
createOptionsElem(newOrderTypeSelectElem, orderTypeList);
// creates a new select tag for product dropdown
const newProductSelectElem = createElementTemplate('select', `product${counter}`);
// Code to switch options depending on ordertype
//------------------------- Does Not Work --------------------------
if(document.getElementById(`ordertype${counter}`).value === 'PH'){
const optionList = optionListPH;
}else{
const optionList = optionListEC;
}
//------------------------------------------------------------------
// generates the content of the dropdown for products and is inserted to the above "productX" select tag
createOptionsElem(newProductSelectElem, optionList);
newDivElem.appendChild(newOrderTypeSelectElem);
newDivElem.appendChild(newProductSelectElem);
// Finally, appends the newly created div tag to the productSection tag.
document.getElementById('productsection').appendChild(newDivElem);
}
function createOptionsElem(selectTag, optionsArr){
const newDefaultOptionTag = document.createElement('option');
newDefaultOptionTag.value = "";
// newDefaultOptionTag.select = false;
newDefaultOptionTag.textContent="Choose your option";
for(let i in optionsArr){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionsArr[i];
newOptionTag.value = optionsArr[i];
// Inserts the option tag in select tag
selectTag.appendChild(newOptionTag);
}
}
// function to create a new element
function createElementTemplate(tagType, idVal, className){
const newElement = document.createElement(tagType);
if(idVal !== undefined)
newElement.id = idVal;
if(className !== undefined)
newElement.classList.add(className);
return newElement;
}
</script>
css_script.html
<style>
.row{
margin-top: 5px;
margin-bottom: 5px;
}
</style>
Code.gs
function doGet(e) {
Logger.log(e);
return HtmlService.createTemplateFromFile('form_basic').evaluate();
}
function include(fileName){
return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
Modification points:
In your script, when a button is clicked, 2 dropdown lists are created. By this, at the following script,
if(document.getElementById(`ordertype${counter}`).value === 'PH'){
const optionList = optionListPH;
}else{
const optionList = optionListEC;
}
in the case of your script, optionListPH is always used to the 1st dropdown list.
And, when you want to change the 2nd dropdown list by changing the 1st dropdown list, it is required to add more script for checking it.
When these points are reflected in your script, how about the following modification?
From:
// Code to switch options depending on ordertype
//------------------------- Does Not Work --------------------------
if(document.getElementById(`ordertype${counter}`).value === 'PH'){
const optionList = optionListPH;
}else{
const optionList = optionListEC;
}
//------------------------------------------------------------------
// generates the content of the dropdown for products and is inserted to the above "productX" select tag
createOptionsElem(newProductSelectElem, optionList);
newDivElem.appendChild(newOrderTypeSelectElem);
newDivElem.appendChild(newProductSelectElem);
// Finally, appends the newly created div tag to the productSection tag.
document.getElementById('productsection').appendChild(newDivElem);
To:
// Code to switch options depending on ordertype
//------------------------- Does Not Work --------------------------
const optionList = optionListPH; // Modified
//------------------------------------------------------------------
// generates the content of the dropdown for products and is inserted to the above "productX" select tag
createOptionsElem(newProductSelectElem, optionList);
newDivElem.appendChild(newOrderTypeSelectElem);
newDivElem.appendChild(newProductSelectElem);
// Finally, appends the newly created div tag to the productSection tag.
document.getElementById('productsection').appendChild(newDivElem);
// I added the below script.
newOrderTypeSelectElem.addEventListener("change", function() {
newProductSelectElem.innerHTML = "";
createOptionsElem(newProductSelectElem, this.value === 'PH' ? optionListPH : optionListEC);
});
When this modification is reflected in your script, when a button is clicked, 2 dropdown lists are created. And, when 1st dropdown list is changed, the 2nd dropdown list is refreshed with new values.
Note:
This modification is for your showing script. When you change your script, this script might not be able to be used. Please be careful about this.
Consider the following hierarchy in DOM
<div class="bodyCells">
<div style="foo">
<div style="foo">
<div style="foo1"> 'contains the list of text elements I want to scrape' </div>
<div style="foo2"> 'contains the list of text elements I want to scrape' </div>
</div>
<div style="foo">
<div style="foo3"> 'contains the list of text elements I want to scrape' </div>
<div style="foo4"> 'contains the list of text elements I want to scrape' </div>
</div>
By using class name bodyCells, I need to scrape out the data from each of the divs one at a time (i.e) Initially from 1st div, then from the next div and so on and store it in separate arrays. How can I possibly achieve this? (using puppeteer)
NOTE: I have tried using class name directly to achieve this but, it gives all the texts in a single array. I need to get data from each tag separately in different arrays.
Expected output:
array1=["text present within style="foo1" div tag"]
array2=["text present within style="foo2" div tag"]
array3=["text present within style="foo3" div tag"]
array4=["text present within style="foo4" div tag"]
As you noted, you can fetch each of the texts in a single array using the class name. Next, if you iterate over each of those, you can create a separate array for each subsection.
I created a fiddle here - https://jsfiddle.net/32bnoey6/ - with this example code:
const cells = document.getElementsByClassName('bodyCells');
const scrapedElements = [];
for (var i = 0; i < cells.length; i++) {
const item = cells[i];
for (var j = 0; j < item.children.length; j++) {
const outerDiv = item.children[j];
const innerDivs = outerDiv.children;
for (var k = 0; k < innerDivs.length; k++) {
const targetDiv = innerDivs[k];
scrapedElements.push([targetDiv.innerHTML]);
}
}
}
console.log(scrapedElements);
I'm creating an Dynamic form in angular js and when I'm adding new input fields as table row,and when pushing these objects into an array, previous element is replaced with copy of new element. Keys are same but values are different and also adding 'id' key before pushing into array.
JS
else if (el.type === 4) { //table
var x = 0;
$scope.row = []; //to store KEY OF table
$scope.thead = []; //store the heading of the table | also to make row structure
$scope.myFm[el.value] = []; //store row of table [ INVOICE ] myFm.invoice
$scope.colInput = {}; //values of input of each row
$scope.colInput.id = 0;
$scope.rowIndex = 0;
//iterate over column_heading
el.column_heading.forEach(function(elem) { //objects in column_heading
$scope.row[x] = elem.val; //the object with key names of row
$scope.thead.push(elem); //column headings
x++;
})
//pusing each row to myFm[el.value] | invoice
$scope.addNew = function(rowObj) {
// $scope.rowIndex++;
console.log('ROW ', rowObj);
rowObj.id = $scope.rowIndex;
$scope.myFm[el.value].push(rowObj);
console.log("Invoice", $scope.myFm[el.value]);
$scope.rowIndex++;
console.log("ROW", rowObj);
}
var row = "<tr ng-repeat='r in myFm." + el.value + " track by id' ><td ng-repeat='i in row'><input ng-model='colInput[i]' class='form-control' placeholder='Enter {[{ i }]}'></td></tr>"
item = "<label>" + el.heading + "<button ng-click='addNew(colInput)' class='m-l-lg btn font-bold'>ADD NEW</button></label> <table class='table'><thead><th ng-repeat='th in thead'>{[{ th.name }]}</th><thead>" + "<tbody>" + row + "</tbody><table>";
}
return item
}
// adding each element from list to DOM. $compile is needed to add the modified element to DOM
$scope.data.forEach(function(el) { //traversing over json object from the server
var item = verifyItem(el);
var linkFn = $compile(item);
var content = linkFn($scope);
element.append(content);
});
// adding the submit button to DOM
var linkFn = $compile('<button type="submit" ng-click="submitFm()" class="m- t-lg m-b-lg btn btn-danger">Submit </button>');
var content = linkFn($scope);
element.append(content);
When i',m passing 'colInput' to the 'addNew' function, and adding 'id' key each time i push new object to array '$scope.myFm[el.value]', the duplicates are being created ie: the newly added is replacing the previous objects, hence i cant 'ng-repeat' it by 'track by id'.
CONSOLE
Invoice Array [ Object, Object, Object ]
these three objects have values of last pushed object.
how do i fix it.
Trying to display a sorted list in a div. But I get only an empty div.
HTML
<div id="contentDmChat" data-win-control="WinJS.UI.ListView">
</div>
JS-Code:
contentDmChat.itemTemplate = myTemplate;
contentDmChat.layout = WinJS.UI.ListLayout;
contentDmChat.tapBehavior = 'directSelect';
contentDmChat.selectionMode = 'single';
contentDmChat.itemDataSource = userMs;
List for data source has elements.
Any idea?