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 !
Related
I did live search by using ajax and have other jquery customizations (Tilt.js etc..) for my card component.
I get search results successfully but it doesn't have whole js customizations .
Ajax
$(document).ready(function() {
$('#location , #sector').on('change',function(){
var location = $('#location').val();
var sector = $('#sector').val();
$.ajax({
url:'search',
type:'GET',
data:{
'location':location,
'sector':sector,
},
success:function(data){
$('#content').html(data);
}
})
}) });
Component that returns from Controller
$output ='';
foreach($data as $post){
$output .='
<div class="card mb-4" id="card" data-tilt data-tilt-max="5" data-tilt-glare data-tilt-max-glare="0.2">
<div class="card-body">
<div class="card my-2 rounded shadow item" role="button" id="'.$post->id.'" >
<div class="row no-gutters">
<div class="col-sm-2 pt-3 pl-2">
<img src="'.$post->image.'" class="img-fluid resim" alt="...">
</div>
<div class="col-sm-10">
<div class="card-body">
<h4 style="font-weight: bolder;">'. $post->company_name.'</h4>
<h5 class="card-title" style="font-weight: bold;">'. $post->job_title.'</h5>
<p class="card-text">'. $post->description.'.</p>
<div class="row">
<div class="col-sm"><div class="rounded-pill text-white text-center py-2 sector " style="background-color: #003777;"> '.$post->sector.'</div></div>
<div class="col-sm"><div class="rounded-pill text-white text-center py-2 location " style="background-color: #003777;"> '.$post->location.'</div></div>
<div class="col-sm"><div class="rounded-pill text-white text-center py-2 " style="background-color: #003777;"> Apply Now!</div></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
';
}
This is due to javascript only loads once the document has finished loading, It then scans all of your dom elements for the elements and adds the listeners, If you are loading dom elements in after this has happened they will not have the event listeners. To get around this there are a few ways but one of the easiest is
$(document).ready(function(){
$('body').on('click','.js-card',function(){
// This body click function will only trigger if the element has the class js-card.
});
});
Another way is to add the onclick to the elements you are loading in <button onClick="yourGlobalFunction">
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
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}}">
I have the following HTML :
I'm trying to send the <p>{{ $comment->comment }}</p> to a Jquery function, upon clicking on the Edit button. I need help in completing the below structure :
Comment = event.target.parentNode.childNodes[1];
<div class=" p-3 border-top border-bottom bg-light">
<div class="d-flex align-items-center osahan-post-header">
<div class="dropdown-list-image mr-3 mb-auto"><img class="rounded-circle" src="img/p8.png" alt=""></div>
<div class="mr-1">
<div class="text-truncate h6 mb-3">{{ $comment->user->first_name }} {{ $comment->user->last_name }}</div>
<p>{{ $comment->comment }}</p>
</div>
<span class="ml-auto mb-auto">
<div class="text-right text-muted pt-1 small">{{ $comment->created_at}}</div>
</span>
</div>
<div class="post" align="right" data-postid="{{ $comment->id }}">
Edit
</div>
</div>
</div>
If you would fix your invalid HTML (as already mentioned in a comment, a <div> can't be inside a <span>), you could get the comment as follows:
document.getElementById("eid").onclick = function(e) {
let comment = e.target.closest(".p-3").getElementsByTagName("p")[0].innerHTML;
console.log(comment);
};
or, if you would use jQuery:
$("#eid").on("click", function(){
let comment = $(this).closest(".p-3").find("p").text();
console.log(comment);
});
I'm developing a chatbox and I have the chat messages hardcoded for the moment.
<!-- Reciever Message-->
<div class="media w-50 ml-auto mb-3">
<div class="media-body">
<div class="bg-primary rounded py-2 px-3 mb-2">
<p class="text-small mb-0 text-white">Test chat</p>
</div>
</div>
</div>
I have a form with a simple input box.
<form action="#" class="bg-light">
<div class="input-group">
<input type="text" placeholder="Type a message" aria-describedby="button-addon2" class="form-control rounded-0 border-0 py-4" id="message">
<div class="input-group-append">
<button id="button-addon2" type="submit" class="btn btn-link" onclick="addText()"> <i class="fa fa-paper-plane"></i></button>
</div>
</div>
</form>
What I want is a way to display the text entered in the text box as the receive message div when the form is submitted. Any suggestions as to how to do it. Thanks in advance.
This is really a design question, not a technical one. Technically speaking you just do exactly what you are doing ... and then put a "chat bubble graphic" as the background-image style of .bg-light.