JavaScript trying to append to HTML not working - javascript

I am trying to create a simple eCommerce website with HTML, CSS, and JavaScript. When a user adds an item to their cart I add that item to local storage and I want when the user goes to their cart, all the items in local storage are read and then displayed to the cart. Whenever I try to append I get this. Instead of displaying the HTML it displays a string of all the HTML?
function getCartItems() {
var items = JSON.parse(localStorage.getItem("cartItems"));
console.log({ items });
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
var cartRow = document.createElement("div");
// cartRow.classList.add("cart-row");
var cartItems = document.getElementsByClassName("cart-items")[0];
var cartRowContents = ` <li class="list-group-item d-flex flex-column">
<div class="row">
<div class="col col-lg-4">
<img
src="${items[i].image}"
alt="${items[i].name}"
class="d-block mx-auto"
/>
</div>
<div class="col col-lg-2 text-center">
<h5 class="mt-4 flex-wrap">${items[i].name}</h5>
<p>Size: 10.5</p>
<h2><span class="badge badge-danger">$189.99</span></h2>
</div>
<div class="col mt-4 text-center">
<p class="font-weight-bold">Quantity</p>
<input type="number" value="1" class="pl-2 w-50 rounded cart-quantity" />
<button
class="btn border border-none mx-5 mt-3 mt-lg-0 remove-item"
>
<i class="far fa-trash-alt"> </i>
</button>
</div>
</div>
</li>`;
cartRow.innerText = cartRowContents;
cartItems.append(cartRow);
}
}
Here is the code for my HTML
<!-- Cart -->
<div class="card m-5 border border-none mw-50">
<div class="card-header text-center text-white bg-primary">
Your Order
</div>
<ul class="list-group list-group-flush cart-items">
<li class="list-group-item d-flex flex-column">
<div class="row">
<div class="col col-lg-4">
<img
src="./images/products/air-max-270.jpg"
alt="Air Max 270"
class="d-block mx-auto"
/>
</div>
<div class="col col-lg-2 text-center">
<h5 class="mt-4 flex-wrap">Nike Air Max 270</h5>
<p>Size: 10.5</p>
<h2><span class="badge badge-danger">$189.99</span></h2>
</div>
<div class="col mt-4 text-center">
<p class="font-weight-bold">Quantity</p>
<input type="number" value="1" class="pl-2 w-50 rounded cart-quantity" />
<button
class="btn border border-none mx-5 mt-3 mt-lg-0 remove-item"
>
<i class="far fa-trash-alt"> </i>
</button>
</div>
</div>
</li>
</ul>

Call appendChild with innerHTML:
var cartItems = document.getElementsByClassName("cart-items")[0];
var cartRow = document.createElement("div");
cartRow.innerHTML = cartRowContents;
cartItems.append(cartRow);
Note: innerHTML is only destructive when used in combination with the += operator, as it causes a DOM refresh. It's all right to use it with createElement, as you're only changing the child's innerHTML, not the entire DOM. Reference

It seems you have confused Element.innerHTML with HTMLElement.innerText, as the latter sets your String to be the Node's actual text, not its HTML.
However, since it is discouraged to use Element.innerHTML for manipulating a Node's HTML, you should instead use Element.insertAdjacentHTML() instead.

This is because you are using innerText. You can use innerHtml instead but it's not recommended.

The way you are doing this, the only way you can pull it off is by using innerHTML like your last answer. However, if you want to do it the 'recommended' way, I would recommend using something called HTML DOM. You can recode all that you did simply by using the concept of creating elements and then appending them to each other and, finally, your cart. Here is the simple concept:
https://www.w3schools.com/js/js_htmldom.asp

Related

Create a dynamic div with JavaScript

I have created a page of feeds in which a new post should be created and shown in the user's feed. Lets say the div will look like this
In the textarea the data is entered and then on click of the post button the lower div is created
I have done this in javascript but the name, image, all data is simply entered by me but it should come from the controller I cant use the simple approach like I have done in HTML page how can it be done in javascript?
<body>
<textarea class="form-control border-0 p-0 fs-xl" rows="4" id="input" placeholder="What's on your mind Codex?..."></textarea>
<button class="btn btn-info shadow-0 ml-auto " id="submit" onclick="addCode()">Post</button>
<div id="add_after_me">
<div class="test " >
</div>
</div>
<script>
$('#submit').click(function () {
var text = $('#input').val();
$('#newDivs').append('<div class="test">' + text + '</div>');
});
function addCode() {
document.getElementById("add_after_me").insertAdjacentHTML("afterend",
'<div class="card mb-g"> < div class= "card-body pb-0 px-4" ><div class="d-flex flex-row pb-3 pt-2 border-top-0 border-left-0 border-right-0"><div class="d-inline-block align-middle status status-success mr-3"> <span class="profile-image rounded-circle d-block" style="background-image:url(); background-size: cover;"></span> </div> <h5 class="mb-0 flex-1 text-dark fw-500"> Dr. John Cook PhD <small class="m-0 l-h-n">Human Resources & Psychiatry Division</small></h5><span class="text-muted fs-xs opacity-70"> 3 hours </span> </div> <div class="pb-3 pt-2 border-top-0 border-left-0 border-right-0 text-muted " id="newDivs"> </div> </div ></div > ');
}
</script>
</body>
here is my code
I'm assuming that you have a Controller that can receive POST data, will handle it, then will respond an JSON with all the processed data that you want your Javascript to display.
We will use simple Ajax with jQuery here. We will start by sending the form via post to your controller when you submit the form, then we will assume that your controller respond a json with the same data once it's done. Then javascript will read the Json responded, and update the DOM.
Here is your code :
<body>
<textarea class="form-control border-0 p-0 fs-xl" rows="4" id="input" placeholder="What's on your mind Codex?..."></textarea>
<button class="btn btn-info shadow-0 ml-auto " id="submit" onclick="addCode()">Post</button>
<div id="add_after_me"></div>
<script>
$('#submit').click(function () {
$.post('/your-controller', {
text: $('#input').val()
}, function(data) {
const json = jQuery.parseJSON(data)
addCode(json)
})
});
function addCode(data) {
const addAfterMe = $("#add_after_me")
const template = `
<div class="card mb-g">
<div class= "card-body pb-0 px-4">
<div class="d-flex flex-row pb-3 pt-2 border-top-0 border-left-0 border-right-0">
<div class="d-inline-block align-middle status status-success mr-3">
<span class="profile-image rounded-circle d-block" style="background-image:url('${data.image}'); background-size: cover;"></span>
</div>
<h5 class="mb-0 flex-1 text-dark fw-500">
${data.fullname}
<small class="m-0 l-h-n">${data.department}</small>
</h5>
<span class="text-muted fs-xs opacity-70">
${data.time}
</span>
</div>
<div class="pb-3 pt-2 border-top-0 border-left-0 border-right-0 text-muted" id="newDivs">${data.text}</div>
</div>
</div>`
addAfterMe.append(template)
}
</script>
</body>
To create your "card", I use "Template Literals" javascript standard. But feel free to use whatever strategy you want.
So, each time that you will submit your form, the text will be sent to the Controller. Assuming that your controller will response this JSON :
{
'text': "Lorem Ipsum",
'image': "https://url-to-your-profile-image.com/image.png",
'fullname': 'Dr. John Cook PhD',
'department': 'Human Resources & Psychiatry Division',
'time': '3 hours'
}
And voila :)
I hope it helps !

Showing a button that pushes all other elements to the side (CSS Transition)

Basically, I'm having cards that have a height set by the flex behaviour. I'd like to add a button from the side that is only shown when the card is hovered so the button would come out from the right side of the container with a transition and start expanding and pushing all other content to the left until it finishes expanding. Therefore, I've looked for hours and I tried many things out and I couldn't find a solution. Could someone please help me out on this? here is my code, I'm using Bootstrap 5. Here is the UI I created
Here is my code . I'm using VueJS and my data is coming from an API.
<template>
<div class="d-flex col-12 flex-column bd-highlight mb-3">
<div class=" d-flex border border-dark col-12 flex-column" v-for="(question,index) in questions" :key="question + index">
<div class="d-flex col-12 justify-content-between">
<div>
<span class="text-wrap text-break">{{question.description}}</span>
</div>
<div class="d-flex">
<span :class="question.complexity.toLowerCase() === 'easy' ? 'badge bg-success align-self-start' : question.complexity.toLowerCase() === 'medium' ? 'badge bg-warning align-self-start' : 'badge bg-danger align-self-start' ">{{question.complexity}}</span>
</div>
</div>
<div class="d-flex flex-wrap">
<div class="p-2" v-for="(tag,index1) in question.tags" :key ="tag + index1">
<span class="badge bg-dark text-white"><i :class="'devicon-'+tag.nom.toLowerCase()+'-plain'"></i> {{tag.nom}}</span>
</div>
<div class="align-items-center d-flex w-100 justify-content-end">
<span>
<i class="fas fa-stopwatch"></i> {{question.duree}} secs </span></div>
</div>
</div>
</div>
</template>
Here is my UI
Expected Result ( Buttons should be with the same size )

Apply different styles to bootstrap card

I'm working with Angular 9 with a Bootstrap 4 card applying NGFOR to paint as many elements as come from the database.
I have the following array with different styles for that card and I would like them to be applied to each one in a random way.
public color_border = ["border-left-warning", "border-left-info", "border-left-primary"]
The card code is as follows: the div card border-left-info has to be changed. I have tried a new NGFOR but it duplicates everything.
<!-- Pending Requests Card Example -->
<div class="col-xl-3 col-md-6 mb-4" *ngFor="let data of miDataInterior.DatagreenhouseRecuperado; let i = index">
<div class="card border-left-info shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{data.medidas[0].sensor_type[0].name_comun}}</div>
<font SIZE=3> {{data.medidas[0].marca}} </font>
<font SIZE=3>({{data.medidas[0].recvTime | date:'dd-MM-yy h:mm:ss a'}})</font>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{data.medidas[0].attrValue | number:'1.0-1'}} {{data.medidas[0].sensor_type[0].medida}}</div>
</div>
<div class="col-auto">
<i class="fas fa-chart-bar fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
How could I apply what is contained in the color_border variable in that div?
Error:
<!-- Pending Requests Card Example -->
<div class="col-xl-3 col-md-6 mb-4" *ngFor="let data of miDataInterior.DatagreenhouseRecuperado; let i = index">
<div *ngFor="let color_border of color_border" class="card {{color_border}} shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{data.medidas[0].sensor_type[0].name_comun}}</div>
<font SIZE=3> {{data.medidas[0].marca}} </font>
<font SIZE=3>({{data.medidas[0].recvTime | date:'dd-MM-yy h:mm:ss a'}})</font>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{data.medidas[0].attrValue | number:'1.0-1'}} {{data.medidas[0].sensor_type[0].medida}}</div>
</div>
<div class="col-auto">
<i class="fas fa-chart-bar fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
Thanks for your help.
EDIT
I am testing directly on NGCLASS, the problem is that it only shows the style of the last element in the array. How can I fix this?
<div class="card shadow h-100 py-2" [ngClass]="['border-left-primary', 'border-left-info', 'border-left-warning']">
Alternate border
[ngClass]="color_border[i%3]"
A random you need make a function (you can not use Math inside the .html)
[ngClass]="getRandomColor()"
getRandomColor()
{
return this.color_border[Math.floor(Math.random()*this.color_border.length]
}
If you miDataInterior.DatagreenhouseRecuperado has a property "color" from 0 to 2 you can use
[ngClass]="color_border[data.color]"
NOTE there're severals ways to use [ngClass], see the docs
Try this..
<div *ngFor="let color_border of color_border" class="card shadow h-100 py-2 " [ngClass]="{{color_border}}">

HTML and Javascript search bootstrap cards

Javascript returning : "Uncaught TypeError: Cannot read property 'innerText' of null" while typing on search form.
I have a page with some Bootstrap cards, and I want to filter the cards by name.
I have tried to get "card-title" element class to validate the search filter.
HTML code:
<div class="container">
<div class="row">
<div class="col-sm-4 mb-4">
<input type="text" id="myFilter" class="form-control" onkeyup="myFunction()" placeholder="Search for card name...">
</div>
</div>
<div class="row" id="myProducts">
<div class="col-md-4">
<div class="card">
<div class="card-header bg-dark d-sm-flex justify-content-sm-between align-items-sm-center">
<div class=" card-title">
<a href="#" style="color:white" class="display-inline- block" onmouseover="this.style.color='#00e6ac'" onmouseout="this.style.color='#fff'">
<strong>Card 1</strong>
</a>
</div>
</div>
<div class="card-body bg-light">
0000x01
</div>
<div class="card-footer bg-white d-flex justify-content-between">
<div>
<i class="icon-arrow-right5 mr-2"></i>Card number one
</div>
</div>
</div>
<div class="card">
<div class="card-header bg-dark d-sm-flex justify-content-sm-between align-items-sm-center">
<div class=" card-title">
<a href="#" style="color:white" class="display-inline- block" onmouseover="this.style.color='#00e6ac'" onmouseout="this.style.color='#fff'">
<strong>Card 2</strong>
</a>
</div>
</div>
<div class="card-body bg-light">
0000x02
</div>
<div class="card-footer bg-white d-flex justify-content-between">
<div>
<i class="icon-arrow-right5 mr-2"></i>Card number two
</div>
</div>
</div>
</div>
<!-- /transparent header, white footer -->
</div>
</div>
Javascript
function myFunction() {
var input, filter, cards, cardContainer, title, i;
input = document.getElementById("myFilter");
filter = input.value.toUpperCase();
cardContainer = document.getElementById("myProducts");
cards = cardContainer.getElementsByClassName("card");
for (i = 0; i < cards.length; i++) {
title = cards[i].querySelector("card-title");
if (title.innerText.toUpperCase().indexOf(filter) > -1) {
cards[i].style.display = "";
} else {
cards[i].style.display = "none";
}
}
}
also testing on:
https://codepen.io/pratykus/pen/WNeJpyK
Every time I type on filter box I got incremented error:
(6) Uncaught TypeError: Cannot read property 'innerText' of null
When you use .querySelector you should specify the class or the element. In your case your element is the div and your class that you're trying to access is card-title, so change:
title = cards[i].querySelector("card-title");
to:
title = cards[i].querySelector(".card-title");
If you are passing a CSS class as the selector to querySelector(), then you have to append it with dot .
title = cards[i].querySelector(".card-title");
Make this change to fix the issue.

AngularJs - On ng-click all items get affected

I'm trying to change the scope when i click on the element but when i do that all the elements get's changed
What im trying to accomplish is when i click on one of the div, i want te color of the div to change to red. this part works fine. Then i also want to the scope to change when i click on one of the divs. What is happening here is that all the scopes are changing.
<div class="col-md-3 col-sm-6 mb-3" ng-repeat="student in stuRegister.students" ng-click="stuRegister.absneceChange($index, absence)">
<div id="myDIV{{$index}}" class="card text-white bg-success o-hidden h-100" data-index="{{$index}}">
<div class="card-body">
<div class="mr-5" >
<p>{{$index + 1}}. <strong>{{student.name}}</strong></p></div>
<div class="mr-5" data-ng-model-options="stuRegister.aData.role" ><strong ng-bind="absence">Status: {{absence[0]}}</strong></div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">Indmeld fravær</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
</div>
Js:
$scope.absence = "Tilstede";
this.absneceChange = function(index, absence){
var element = document.getElementsByClassName("card");
$scope.absence = $scope.absence === "Tilstede" ? "Fravær" : "Tilstede";
element[index].classList.toggle("bg-danger");
element[index].classList.toggle("bg-warning");
}

Categories