<template> clone but with texts from user input - javascript

I am trying to create a comment section for my page, I used the template element to create the box and format for my user's pic and name but i'm having difficulties adding the text received from the user to get into the box. right now it creates the box and just puts the text outside/under it. How can I create a element to store inside the template?
function postComment() {
//Clone new box for comment
var temp = document.getElementsByTagName("template")[0];
var clone = temp.content.cloneNode(true);
var newComment = document.getElementById("new-comment");
newComment.appendChild(clone)
//Get comment
var userComment = document.getElementById("comment-box").value;
var text = document.createElement('p');
text.innerHTML = userComment;
newComment.appendChild(text)
//reset the comment box
document.getElementById("comment-box").value = "";
}
var post = document.getElementById("post");
post.addEventListener("click", function(e) {
e.preventDefault();
postComment()
})
.comment-box,
.post-comment .list {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 2px black;
}
.comment-section {
width: 100%;
height: auto;
margin: 0 auto;
}
.post-comment .list {
width: 100%;
margin-bottom: 12px;
}
.post-comment .list .user {
display: flex;
padding: 8px;
overflow: hidden;
}
.post-comment .list .user img {
height: 38px;
width: 38px;
margin-right: 10px;
border-radius: 50%;
}
.comment-section .name {
text-transform: uppercase;
}
.post-comment .list .day {
font-size: 12px;
}
.post-comment {
padding: 0 0 15px 58px
}
#comment-box {
border: none;
border-radius: 5px;
}
.comment-box .user {
display: flex;
width: min-content;
}
.comment-box .image img {
width: 24px;
height: 24px;
margin-right: 10px;
border-radius: 50%;
}
<div class="row">
<div class="comment-section">
<div class="post-comment">
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/ok.webp"></div>
<div class="user-name">
<div class="name">TOM</div>
<div class="day">100 days ago</div>
</div>
</div>
<div class="comment">LOREM IPSUN DABUN VUB</div>
</div>
<template>
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/Animal-Crossing-Tom-Nook-with-Money.jpg"></div>
<div class="user-name">
<div class="name">Tom Nook</div>
<div class="day">1 second ago</div>
</div>
</div>
</div>
</template>
<div id="new-comment"></div>
<div class="comment-box">
<div class="user">
<div class="user-image"><img src="./images/OK.webp"></div>
<form>
<textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
<button id="post">Comment</button>
</form>
</div>
</div>
</div>
</div>
</div>

Try this and see if this suits your requirements:
function postComment() {
//Get comment
var userComment = document.getElementById("comment-box").value;
var html = '<div class="list">' +
'<div class="user">' +
'<div class="user-image"><img src="./images/Animal-Crossing-Tom-Nook-with-Money.jpg"></div>' +
'<div class="user-name">' +
'<div class="name">Tom Nook</div>' +
'<div class="day">1 second ago</div>' +
'</div>' +
'</div>' +
'<div id="new-comment">' + userComment + '</div>' +
'</div>';
var template = document.getElementsByTagName("template")[0];
template.insertAdjacentHTML("afterend", html);
//reset the comment box
document.getElementById("comment-box").value = "";
}
var post = document.getElementById("post");
post.addEventListener("click", function(e) {
e.preventDefault();
postComment()
})
.comment-box,
.post-comment .list {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 2px black;
}
.comment-section {
width: 100%;
height: auto;
margin: 0 auto;
}
.post-comment .list {
width: 100%;
margin-bottom: 12px;
}
.post-comment .list .user {
display: flex;
padding: 8px;
overflow: hidden;
}
.post-comment .list .user img {
height: 38px;
width: 38px;
margin-right: 10px;
border-radius: 50%;
}
.comment-section .name {
text-transform: uppercase;
}
<div class="row">
<div class="comment-section">
<div class="post-comment">
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/ok.webp"></div>
<div class="user-name">
<div class="name">TOM</div>
<div class="day">100 days ago</div>
</div>
</div>
<div class="comment">LOREM IPSUN DABUN VUB</div>
</div>
<template></template>
<div class="comment-box">
<div class="user">
<div class="user-image"><img src="./images/OK.webp"></div>
<form>
<textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
<button id="post">Comment</button>
</form>
</div>
</div>
</div>
</div>
</div>

Related

Show multiple file thumbnail on custom dropzone

I created custom dropzone in order to upload my files as the following example
function readFile(input) {
debugger;
if (input.files && input.files[0]) {
var reader = new FileReader();
for (let i = 0; i < input.files.length; i++) {
reader.onload = function(e) {
var htmlPreview =
'<img width="100" src="' +
e.target.result +
'" />' +
"<p>" +
input.files[i].name +
"</p>";
var wrapperZone = $(input).parent();
var previewZone = $(input)
.parent()
.parent()
.find(".preview-zone");
var boxZone = $(input)
.parent()
.parent()
.find(".preview-zone")
.find(".box")
.find(".box-body");
wrapperZone.removeClass("dragover");
previewZone.removeClass("hidden");
// boxZone.empty();
boxZone.append(htmlPreview);
};
}
reader.readAsDataURL(input.files[0]);
}
}
function reset(e) {
e.wrap("<form>")
.closest("form")
.get(0)
.reset();
e.unwrap();
}
$(".dropzone").change(function() {
readFile(this);
});
$(".dropzone-wrapper").on("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
$(this).addClass("dragover");
});
$(".dropzone-wrapper").on("dragleave", function(e) {
e.preventDefault();
e.stopPropagation();
$(this).removeClass("dragover");
});
$(".remove-preview").on("click", function() {
var boxZone = $(this)
.parents(".preview-zone")
.find(".box-body");
var previewZone = $(this).parents(".preview-zone");
var dropzone = $(this)
.parents(".form-group")
.find(".dropzone");
boxZone.empty();
previewZone.addClass("hidden");
reset(dropzone);
});
.container {
padding: 50px 100px;
}
.box {
position: relative;
background: #ffffff;
width: 100%;
}
.box-header {
color: #444;
display: block;
padding: 10px;
position: relative;
margin-bottom: 10px;
}
.box-tools {
position: absolute;
right: 10px;
top: 5px;
}
.dropzone-wrapper {
border: 2px dashed #91b0b3;
color: #92b0b3;
position: relative;
height: 150px;
}
.dropzone-desc {
position: absolute;
margin: 0 auto;
left: 0;
right: 0;
text-align: center;
width: 40%;
top: 60px;
font-size: 16px;
}
.dropzone,
.dropzone:focus {
outline: none !important;
width: 100%;
cursor: pointer;
}
.input-file {
position: absolute;
width: 100%;
height: 150px;
opacity: 0;
}
.dropzone-wrapper:hover,
.dropzone-wrapper.dragover {
background: #ecf0f5;
}
.preview-zone {
text-align: center;
}
.preview-zone .box {
box-shadow: none;
border-radius: 0;
margin-bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row" id="10secs">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">10sec</h4>
</div>
<div class="card-body">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="preview-zone hidden">
<div class="box box-solid">
<div class="box-header with-border">
<div><b>Preview</b></div>
<div class="box-tools pull-right">
<button type="button" class="btn btn-danger btn-xs remove-preview">
<i class="fa fa-times"></i> Reset
</button>
</div>
</div>
<div class="box-body"></div>
</div>
</div>
<div class="dropzone-wrapper">
<div class="dropzone-desc">
<i class="glyphicon glyphicon-download-alt"></i>
<div>Choose an image file or drag it here.</div>
</div>
<input type="file" class="dropzone input-file" multiple asp-for="#Model.Files10" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
As you can see it is a multiple-input file, so you can upload multiple files in the same dropzone.
as you can see in the readFile javascript function, I create the thumbnail, the problem is when selecting more than one file, it only shows one thumbnail, how can I display each of them each next to the other as:
Regards

Assign TWO Images to Radio Button

Hi so I have this "product" page (on Fiddle) where I have multiple radio boxes in two classes .choosesize and .choosetea. I want to set up my code where if the 8oz radio button is selected then one set of pictures will appear for all the tea selections and if the 16oz radio button is selected another set of pictures will appear for the tea selections.
I have assigned the small and big images to each tea option but I do not know how to show the small pictures if the small 8oz option is selected.
While you don't have all the "combined" images, I have added a possible solution.
var size = "small"
var teatype = "green"
$('.choosetea input').on('click', function() {
teatype = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
So this will comebine size and teatype, So each image will have the data-image where it should be size_teatype
$(document).ready(function() {
var size = "small"
var teatype = ""
$('.choosetea input').on('click', function() {
teatype = "_"+$(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
//local storage color
//local storage size
// add the value of the added radio boxes in the text box
$('.radios1').change(function(e) {
var selectedValue = parseInt($(this).val());
selectedValue += parseInt($(".radios2").val());
$('#amount').val('$' + selectedValue)
});
//add to cart
});
const sizeSelector = 'input:radio[id=small]';
const colorSelector = 'input:radio[id=green]';
const cartSelector = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const SMALL = 20;
const GREEN = 0;
const CARTBUTTON = 5;
function validityCheck() {
let $size = $(`${sizeSelector}`);
let $color = $(`${colorSelector}`);
let size_flag = $size.is(':checked');
let color_flag = $color.is(':checked');
$('#itemdv1A').toggle(size_flag && color_flag) && $('#itemdv2A').toggle(size_flag && color_flag) && $('#yourbutton').toggle(size_flag && color_flag);
}
});
const sizeSelector1 = 'input:radio[id=small]';
const colorSelector1 = 'input:radio[id=chamomile]';
const cartSelector1 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const CHAMOMILE = 1;
function validityCheck() {
let $size1 = $(`${sizeSelector1}`);
let $color1 = $(`${colorSelector1}`);
let size_flag1 = $size1.is(':checked');
let color_flag1 = $color1.is(':checked');
$('#itemdv1B').toggle(size_flag1 && color_flag1) && $('#itemdv2B').toggle(size_flag1 && color_flag1) && $('#yourbutton').toggle(size_flag1 && color_flag1)
};
});
const sizeSelector2 = 'input:radio[id=small]';
const colorSelector2 = 'input:radio[id=oolong]';
const cartSelector2 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const OOLONG = 2;
function validityCheck() {
let $size2 = $(`${sizeSelector2}`);
let $color2 = $(`${colorSelector2}`);
let size_flag2 = $size2.is(':checked');
let color_flag2 = $color2.is(':checked');
$('#itemdv1C').toggle(size_flag2 && color_flag2) && $('#itemdv2C').toggle(size_flag2 && color_flag2) && $('#yourbutton').toggle(size_flag2 && color_flag2);
}
});
document.querySelector('#yourbutton').onclick = function() {
document.querySelector('#itemscart').style.display = "none"
};
/* Basic Styling */
.container {
width: 1200px;
top: 300px;
left: 50px;
padding: 15px;
display: flex;
position: absolute;
}
/* Columns */
.columnleft {
width: 220%;
position: relative;
margin-left: 30px;
}
.columnright {
width: 120%;
top: 10px;
margin-left: 80px;
display: block;
}
/* Left Column */
.columnleft img {
width: 100%;
position: absolute;
opacity: 0;
transition: all 0.3s ease;
}
.columnleft img.active {
opacity: 1;
}
/* Product Description */
.product-description {
border-bottom: 1px solid #E1E8EE;
margin-bottom: 20px;
}
/* Product Color */
.tea-type {
margin-bottom: 30px;
}
.choosetea div {
display: block;
margin-top: 10px;
}
.label {
width: 150px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosetea input {
display: none;
}
.choosetea input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosetea input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosetea input#green+label span {
background-color: #90978b;
}
.choosetea input#chamomile+label span {
background-color: #ffd4a1;
}
.choosetea input#oolong+label span {
background-color: #948e9e;
}
.choosetea input:checked+label span {
background-image: url(check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* SIZE */
.tea-type {
margin-bottom: 30px;
}
.choosesize div {
display: block;
margin-top: 10px;
}
.label {
width: 100px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosesize input {
display: none;
}
.choosesize input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosesize input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosesize input#small+label span {
background-color: #252525;
}
.choosesize input#big+label span {
background-color: #1d1d1d;
}
.choosesize input:checked+label span {
background-image: url(https://noychat.github.io/Folia-Website/check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* Product Price */
.product-price {
margin-top: 40px;
display: flex;
align-items: center;
}
.product-price span {
font-size: 26px;
font-weight: 300;
color: #43474D;
margin-right: 20px;
}
.cart-btn {
display: inline-block;
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
}
.cart-btn:hover {
background-color: black;
}
.cart-btn2 {
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
width: 20px;
position: absolute;
}
#amount {
margin-right: 10px;
display: inline-block;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 40px;
padding-left: 10px;
transition: all .5s;
}
#shoppingcart {
width: 360px;
height: 300px;
/* border: 1px solid red; */
}
.item {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 200px;
height: 30px;
padding-left: 10px;
transition: all .5s;
float: left;
}
.item1 {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 30px;
padding-left: 10px;
transition: all .5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header"></div>
<!--close all header portion-->
<div class="container">
<!-- Left Column---Tea Images -->
<div class="columnleft">
<img data-image="oolong" src="https://noychat.github.io/Folia-Website/oolongbig.png" alt=" Big Oolong Can">
<img data-image="chamomile" src="https://noychat.github.io/Folia-Website/chamomilebig.png" alt="Big Chamomile Can">
<img data-image="green" class="active" src="https://noychat.github.io/Folia-Website/greenteabig.png" alt="Big Green Tea Can">
<img data-image="small" class="active" src="https://noychat.github.io/Folia-Website/foliasmall.png" alt="Small Example Can">
<img data-image="big" src="https://noychat.github.io/Folia-Website/foliabig.png" alt="Big Example Can">
<img data-image="small_chamomile" src="https://noychat.github.io/Folia-Website/chamomilesmall.png" alt="Small Chamomile Can">
<img data-image="small_oolong" src="https://noychat.github.io/Folia-Website/oolongsmall.png" alt="Small Oolong Can">
<img data-image="small_green" src="https://noychat.github.io/Folia-Website/greenteasmall.png" alt="Small Green Tea Can">
</div>
<!-- Right Column -->
<div class="columnright">
<!-- Product Description -->
<div class="product-description">
<span>Folia Tea Collection</span>
<h1>Signature Teas</h1>
<p>We source our tea leaves from around the world. Try our many selections of teas and you will taste the difference.</p>
</div>
<!-- Product Configuration -->
<div class="product-configuration">
<!-- Tea Size -->
<div class="tea-type">
<h3>Size</h3>
<div class="choosesize">
<div>
<input data-image="small" type="radio" id="small" name="size" value="20" class="radios1">
<label for="small"><span></span></label>
<div class="label">8 oz</div>
</div>
<div>
<input data-image="big" type="radio" id="big" name="size" value="40" class="radios1">
<label for="big"><span></span></label>
<div class="label">16 oz</div>
</div>
</div>
<!--CLOSE TEA Size-->
<!-- Tea Type -->
<div class="tea-type">
<h3>Tea Type</h3>
<div class="choosetea">
<div>
<input data-image="green" data-image1="small_green" type="radio" id="green" name="color" value="0" class="radios2">
<label for="green"><span></span></label>
<div class="label">Green Tea</div>
</div>
<div>
<input data-image="chamomile" data-image1="small_chamomile" type="radio" id="chamomile" name="color" class="radios2" value="1">
<label for="chamomile"><span></span></label>
<div class="label">Chamomile Tea</div>
</div>
<div>
<input data-image="oolong" data-image1="small_oolong" type="radio" id="oolong" name="color" class="radios2" value="2">
<label for="oolong"><span></span></label>
<div class="label">Oolong Tea</div>
</div>
</div>
</div>
<!--CLOSE TEA TYPE-->
<h3>Product Pricing</h3>
<div class="product-price">
<input type="text" name="amount" id="amount">
<button type="button" class="cart-btn" id="cartbutton" name="cart" value="5">Add To Cart!</button>
</div>
</div>
</div>
<!--close CONTAINER-->
<div id="shoppingcart">
<h3>Shopping Cart</h3>
<h5>Item and Price</h5>
<div id="itemscart">
<div id="itemdv1A" style="display: none"> <input type="text" name="amount" class="item" value="8oz Green Tea"></div>
<div id="itemdv2A" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1B" style="display: none"> <input type="text" name="amount" class="item" value="8oz Chamomile Tea"></div>
<div id="itemdv2B" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1C" style="display: none"> <input type="text" name="amount" class="item" value="8oz Oolong Tea"></div>
<div id="itemdv2C" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<button style="display: none" type="button" class="cart-btn2" id="yourbutton" name="remove" value="10">x</button>
</div>
</div>

HTML Select item show div and post problem

I am confused. I want two products to be selected. These products will be open by clicking the button. The selection will be made on the screen that opens. And the selected product will replace the button clicked.
I can show the products by clicking the button. I even got the result I wanted as text with jquery. But I used <select> <option> for this. There will be no drop-down list and only one will be selected. The selected image will replace the clicked area. I couldn't :(
$(document).ready(function() {
$(".showbutton, .showbutton img").click(function(event) {
var buttonName = $(this).closest('div').attr('id');
var buttonNo = buttonName.slice(4);
var boxName = "#box" + buttonNo;
$(boxName).fadeIn(300);
});
$(".closebtn").click(function() {
$(".box").fadeOut(200);
});
$(".box").click(function() {
$(".box").fadeOut(200);
});
$(".innerbox").click(function() {
event.preventDefault();
event.stopPropagation();
});
});
div.showbutton {}
div.showbutton:hover {}
.box {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.innerbox {
overflow: scroll;
width: 80%;
height: 80%;
margin: 5% auto;
background-color: white;
border: 3px solid gray;
padding: 10px;
box-shadow: -10px -10px 25px #ccc;
}
#box1 {
position: fixed;
display: none;
width: 400px;
height: 400px;
top: 0;
left: 0;
}
#box2 {
position: fixed;
display: none;
width: 400px;
height: 400px;
top: 0;
left: 0;
}
.closebutton {
width: 20%;
float: right;
cursor: pointer;
}
.closebtn {
text-align: right;
font-size: 20px;
font-weight: bold;
}
.clear {
clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="builder" action="" method="POST">
<div class="showbutton" id="link1">
click for first items
</div>
<div id="box1" class="box">
<div class="innerbox">
<div class="closebutton">
<div class="closebtn">X</div>
</div>
- item1.png - item2.png - item3.png
</div>
</div>
<div class="showbutton" id="link1">
click for second items
</div>
<div id="box1" class="box">
<div class="innerbox">
<div class="closebutton">
<div class="closebtn">X</div>
</div>
- item1.png - item2.png - item3.png
</div>
</div>
JSFIDDLE example of my codes: https://jsfiddle.net/j5fqhat6/
You can add data attribute to your kutu div this will help us to identify from where click event has been occurred .So, whenever your gosterButonu is been clicked you can use this data-id to add selected images text to your gosterButonu div.
Demo Code :
$(document).ready(function() {
$(".gosterButonu, .gosterButonu img").click(function(event) {
var butonAdi = $(this).attr('id');
console.log(butonAdi)
//if on click of button you want to remove active class
// $("div[data-id="+butonAdi+"]").find("li").removeClass("active")
$("div[data-id=" + butonAdi + "]").fadeIn(300);
});
$(".kapatButonu").click(function() {
var data_id = $(this).closest(".kutu").data("id");
$("#" + data_id).text($(this).closest(".icKutu").find("li.active").text())
$(".kutu").fadeOut(200);
});
$(".kutu").click(function() {
$(".kutu").fadeOut(200);
});
$(".icKutu").click(function() {
event.preventDefault();
event.stopPropagation();
});
//on click of li
$(".images li").click(function() {
//remove active class from other lis
$(this).closest(".images").find("li").not(this).removeClass("active")
//add active class to li which is clicked
$(this).addClass("active");
})
});
div.gosterButonu {}
div.gosterButonu:hover {}
.kutu {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.icKutu {
overflow: scroll;
width: 80%;
height: 80%;
margin: 5% auto;
background-color: white;
border: 3px solid gray;
padding: 10px;
box-shadow: -10px -10px 25px #ccc;
}
#kutu1 {
position: fixed;
display: none;
width: 400px;
height: 400px;
top: 0;
left: 0;
}
#kutu2 {
position: fixed;
display: none;
width: 400px;
height: 400px;
top: 0;
left: 0;
}
.kapatButonuCerceve {
width: 20%;
float: right;
cursor: pointer;
}
.kapatButonu {
text-align: right;
font-size: 20px;
font-weight: bold;
}
.clear {
clear: both;
}
ul li {
list-style-type: none
}
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="builder" action="" method="POST">
<div class="gosterButonu" id="link1">
clickfor first items
</div>
<!--added data-id which matched with the div above-->
<div id="kutu1" data-id="link1" class="kutu">
<div class="icKutu">
<div class="kapatButonuCerceve">
<div class="kapatButonu">X</div>
</div>
<div class="clear"></div>
<!--added ul li-->
<ul class="images">
<li>- item1.png</li>
<li> - item2.png </li>
<li>- item3.png</li>
</ul>
</div>
</div>
<div class="gosterButonu" id="link2">
click for second items
</div>
<!--added data-id which matched with the div above-->
<div id="kutu2" data-id="link2" class="kutu">
<div class="icKutu">
<div class="kapatButonuCerceve">
<div class="kapatButonu">X</div>
</div>
<div class="clear"></div>
<ul class="images">
<li>- item1.png</li>
<li> - item2.png </li>
<li>- item3.png</li>
</ul>
</div>
</div>

Dynamically assign properties and values to a javascript object

I am trying to create a week meal planner. At the moment the scenario is the following:
You click on a time of day (breakfast/lunch/dinner) + day of the week;
A list of recipes fades in;
By selecting (clicking) on a recipe you assign this recipe to the day of th week + time of day previously selected.
I want to store all this data into a JS object, ideally I would like to dynamically create the day object with breakfast/lunch/dinner as keys and recipe as the value but I'm a little stuck here. I've created a jsfiddle as a little demo of what I'm trying achieve. The problem is that when I select for e.g. recipe-1 for Monday breakfast it does correctly get stored but then, if I select recipe-2 for lunch - breakfast gets reassinged a value of 0. Can someone help me understand why is this happening and guide me to a better approach? Any suggestion/ help is very much appreciated! Thank you very much!
// find elements
var data_day = '',
time_of_day = '',
recipe = $('.recipes .recipe'),
weekly_recipes = {
'week_day': {}
};
// show list of recipes
$("[data-time]").on("click", function(){
$('.recipes').fadeIn();
time_of_day = $(this).attr('data-time');
data_day = $(this).parents('.column').attr('data-day');
});
recipe.on('click', function(){
var recipe_name = $(this).attr('data-recipe');
weekly_recipes.week_day[data_day] = {
'breakfast': 0,
'lunch': 0,
'dinner': 0
};
$('.recipes').fadeOut();
weekly_recipes.week_day[data_day][time_of_day] = recipe_name;
$('.meal-plan').text(JSON.stringify(weekly_recipes));
console.log(weekly_recipes);
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.column{
width: 25%;
float: left;
padding: 10px;
}
.column strong{
display: block;
margin-bottom: 20px;
}
.column .wrp{
background: white;
}
.column [data-time]{
cursor: pointer;
margin-bottom: 10px;
}
.recipes{
width: 100%;
display: none;
clear: both;
margin-top: 40px;
background: white;
}
.recipes span{
display: block;
cursor: pointer;
margin-top: 10px;
}
.meal-plan{
margin-top: 20px;
background: white;
clear: both;
margin-top: 40px;
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="column" data-day="monday">
<div class="wrp">
<strong>Monday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="tuesday">
<div class="wrp">
<strong>Tuesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="wednesday">
<div class="wrp">
<strong>Wednesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="recipes">
<div class="recipe" data-recipe="recipe-1">
<span data-recipe="recipe-1">recipe 1</span>
</div>
<div class="recipe" data-recipe="recipe-2">
<span data-recipe="recipe-2">recipe 2</span>
</div>
</div>
<div class="meal-plan">
</div>
</div>
You were almost there but the whole issue was that you were resetting the object to default 0 value everytime the user clicks on the recepie.
Instead you need to put some check that if it is already initialized then dont reset it to default.
I have added the below code:
if(!weekly_recipes.week_day.hasOwnProperty(data_day) || Object.keys(weekly_recipes.week_day[data_day]).length === 0){
weekly_recipes.week_day[data_day] = {
'breakfast': 0,
'lunch': 0,
'dinner': 0
};
}
See the working code below:
// find elements
var data_day = '',
time_of_day = '',
recipe = $('.recipes .recipe'),
weekly_recipes = {
'week_day': {}
};
// show list of recipes
$("[data-time]").on("click", function() {
$('.recipes').fadeIn();
time_of_day = $(this).attr('data-time');
data_day = $(this).parents('.column').attr('data-day');
});
recipe.on('click', function() {
var recipe_name = $(this).attr('data-recipe');
console.log(weekly_recipes.week_day[data_day]);
if (!weekly_recipes.week_day.hasOwnProperty(data_day) || Object.keys(weekly_recipes.week_day[data_day]).length === 0) {
weekly_recipes.week_day[data_day] = {
'breakfast': 0,
'lunch': 0,
'dinner': 0
};
}
$('.recipes').fadeOut();
weekly_recipes.week_day[data_day][time_of_day] = recipe_name;
$('.meal-plan').text(JSON.stringify(weekly_recipes));
console.log(weekly_recipes);
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.column {
width: 25%;
float: left;
padding: 10px;
}
.column strong {
display: block;
margin-bottom: 20px;
}
.column .wrp {
background: white;
}
.column [data-time] {
cursor: pointer;
margin-bottom: 10px;
}
.recipes {
width: 100%;
display: none;
clear: both;
margin-top: 40px;
background: white;
}
.recipes span {
display: block;
cursor: pointer;
margin-top: 10px;
}
.meal-plan {
margin-top: 20px;
background: white;
clear: both;
margin-top: 40px;
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="column" data-day="monday">
<div class="wrp">
<strong>Monday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="tuesday">
<div class="wrp">
<strong>Tuesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="wednesday">
<div class="wrp">
<strong>Wednesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="recipes">
<div class="recipe" data-recipe="recipe-1">
<span data-recipe="recipe-1">recipe 1</span>
</div>
<div class="recipe" data-recipe="recipe-2">
<span data-recipe="recipe-2">recipe 2</span>
</div>
</div>
<div class="meal-plan">
</div>
</div>
Your code is very near to work, you only need to take care when the object of some day already exists to not create it again.
See below code, you just create a new day when it doesn't exist, if it already exists, then just add the recipe to the time_of_day of that day
var data_day = '',
time_of_day = '',
recipe = $('.recipes .recipe'),
weekly_recipes = {
'week_day': {}
};
$("[data-time]").on("click", function(){
$('.recipes').fadeIn();
time_of_day = $(this).attr('data-time');
data_day = $(this).parents('.column').attr('data-day');
});
recipe.on('click', function(){
var recipe_name = $(this).attr('data-recipe');
//CHECK FOR DAY EXISTANCE
if (weekly_recipes.week_day[data_day] == null || !weekly_recipes.week_day.hasOwnProperty(data_day)){
weekly_recipes.week_day[data_day] = {
'breakfast': 0,
'lunch': 0,
'dinner': 0
};
}
weekly_recipes.week_day[data_day][time_of_day] = recipe_name;
$('.recipes').fadeOut();
$('.meal-plan').text(JSON.stringify(weekly_recipes));
console.clear()
console.log(weekly_recipes);
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.column{
width: 25%;
float: left;
padding: 10px;
}
.column strong{
display: block;
margin-bottom: 20px;
}
.column .wrp{
background: white;
}
.column [data-time]{
cursor: pointer;
margin-bottom: 10px;
}
.recipes{
width: 100%;
display: none;
clear: both;
margin-top: 40px;
background: white;
}
.recipes span{
display: block;
cursor: pointer;
margin-top: 10px;
}
.meal-plan{
margin-top: 20px;
background: white;
clear: both;
margin-top: 40px;
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="column" data-day="monday">
<div class="wrp">
<strong>Monday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="tuesday">
<div class="wrp">
<strong>Tuesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="column" data-day="wednesday">
<div class="wrp">
<strong>Wednesday</strong>
<div data-time="breakfast">Breakfast</div>
<div data-time="lunch">Lunch</div>
<div data-time="dinner">Dinner</div>
</div>
</div>
<div class="recipes">
<div class="recipe" data-recipe="recipe-1">
<span data-recipe="recipe-1">recipe 1</span>
</div>
<div class="recipe" data-recipe="recipe-2">
<span data-recipe="recipe-2">recipe 2</span>
</div>
</div>
<div class="meal-plan"></div>

jquery filter search needs to search within categories

I'm creating a jquery filter search.
I want to be able to search within a filtered category. I can filter out categories, but if I search within the selected category the search searches through the whole bunch but not only the selected category.
The search is almost working as it should, but I'm not sure how I can implement the search within categories criteria.
Here is a link to a fiddle
Any help or advise would be very much appreciated
$(document).ready(function(){
$("#searchInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#searchFilterDiv div.CompanyDirectoryItem").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
if($('#searchFilterDiv div.CompanyDirectoryItem:visible').length===0){
$('.error').show();
}else{
$('.error').hide();
}
});
});
$(".filter-button").on("click", function(){
var selectItem = $(this).data('category');
filter(selectItem);
});
function filter(e) {
var regex = new RegExp('\\b\\w*' + e + '\\w*\\b');
$('.CompanyDirectoryItem').hide().filter(function () {
return regex.test($(this).data('name'))
}).show();
if($('.CompanyDirectoryItem:visible').length===0){
$('.error').show();
}else{
$('.error').hide();
}
}
$('.box-item').on('click', function(){
$('.box-item').removeClass('selected');
$(this).addClass('selected');
});
.search-form-item{
margin-top: 30px;
background-color: #f9f9f9;
border: 1px solid lightgrey;
margin-bottom: 2em;
padding: 20px;
font-size: .9em;
text-align: left;
}
/* Thjonusta AO */
.boxes-centered{
text-align:center;
}
.box-item{
color: #333;
background-color: #fff;
border: 1px solid #ccc;
padding: 20px 10px;
margin: 1.7em .8em 1.7em .8em;
max-width: 10vw;
font-size: 1.1em;
font-weight: 500;
cursor: pointer;
display:inline-block;
float:none;
text-align:center;
}
.box-item:hover{
border-color: blue;
}
.box-item.selected{
border-color:red;
color:red;
}
.search-form-service {
border: 1px solid lightgray;
margin-left: 8.333%;
margin-right: 8.333%;
background: #fff;}
.search-form-service .form-control {
border-radius: 0 !important;
box-shadow: none;
-webkit-appearance: none;
border: 0;
height: 50px;
font: 18px "DINPro", Arial, sans-serif;
padding: 15px;
color: #4b4b4b; }
.search-form-service .form-control::-moz-placeholder {
color: #4b4b4b;
opacity: 1; }
.search-form-service .form-control:-ms-input-placeholder {
color: #4b4b4b; }
.search-form-service .form-control::-webkit-input-placeholder {
color: #4b4b4b; }
#media (max-width: 767px) {
.search-form-service .form-control {
font-size: 16px;
height: 50px;
padding: 10px 12px; } }
.search-form-service .btn-search {
border-width: 0 0 0 1px; }
.search-form-service .input-group-btn {
z-index: 5; }
.search-form-service.type2 {
max-width: 281px; }
.search-form-service.type2 .form-control {
height: 39px;
padding: 8px 15px; }
.search-form-service.type2 .btn-search {
min-width: 57px;
height: 39px; }
/*Custom Media Quearies */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="container form-container">
<div class="row search-form-item">
<div class="col-md-10 col-md-offset-1 searchtext-input search-form-service">
<input class="form-control" id="searchInput" type="text" placeholder="Search">
</div>
<div class="row boxes-centered">
<div class="col-md-2 col-md-offset-1 box-item filter-button" data-category="EveryCat">Every Category</div>
<div class="col-md-2 box-item filter-button" data-category="Category1">Category1</div>
<div class="col-md-2 box-item filter-button" data-category="Category2">Category2</div>
<div class="col-md-2 box-item filter-button" data-category="Category3">Category3</div>
<div class="col-md-2 box-item filter-button" data-category="Category4">Category4</div>
</div>
</div>
</div><!-- / container -->
<div id="searchFilterDiv">
<div class="CompanyDirectoryItem" data-name="EveryCat, Category1">
<h3>this belongs to Category1</h3>
<p>Some text, more text more text more text </p>
some link
</div>
<div class="CompanyDirectoryItem" data-name="EveryCat, Category2">
<h3>this belongs to Category2</h3>
<p>Some text, more text more text more text </p>
some link
</div>
<div class="CompanyDirectoryItem" data-name="EveryCat, Category3">
<h3>Item belongs to Category3</h3>
<p>Some text, more text more text more text </p>
some link
</div>
<div class="CompanyDirectoryItem" data-name=" EveryCat, Category4">
<h3>Item in Cat 4</h3>
<p> this item belongs to Category4 </p>
some link
</div>
<div class="CompanyDirectoryItem" data-name="EveryCat, Category4, Category1">
<h3> this belongs to 1 and Category4</h3>
<p>Some text, text about this item that belongs to category 1 and 4 </p>
some link
</div>
<div class="CompanyDirectoryItem" data-name="EveryCat, Category3, Category2">
<h3>Item belongs to Category2 and Category3</h3>
<p>Some text, more text more text more text Category2 and Category3 txoeljljl </p>
some link
</div>
<div class="alert alert-error"></div>
<div class="error search-results-box-item" style="display: none;">
<h3>No Results</h3>
<p> Search gave no results, please try again </p>
</div>
</div> <!-- searchFilterDiv ends -->
You want to search from visible sections only:
$("#searchFilterDiv div.CompanyDirectoryItem:visible").filter(function() {
EDIT
To keep searching/filtering functionality I suggest to use detach/attach:
let tmp=[];
function filter(e) {
if(tmp.length>0)
tmp.map(x => x.appendTo($('#searchFilterDiv')));
var regex = new RegExp('\\b\\w*' + e + '\\w*\\b');
$('.CompanyDirectoryItem').detach().filter(function () {
if(regex.test($(this).data('name')))
return true
else
tmp.push($(this))
}).appendTo($('#searchFilterDiv'));
}
and now you can use your initial search/filtering function
$("#searchFilterDiv div.CompanyDirectoryItem").filter(function() {

Categories

Resources