JQuery function works alone, but not when called with AJAX - javascript

I have the following jquery script that is working just fine when standing alone, but does not work whenever I use AJAX to populate the page. Here is the jquery script:
// This section handles adding new links to page //
function appendSection() {
$(this).off('change');
const newSection = $(this).closest('section').clone();
newSection.find('input, select').each((i, el) => {
el.value = '';
el.name = el.name.replace(/\[(\d)\]/, (match, p1) => `[${parseInt(p1) + 1}]`);
});
newSection.on('change', appendSection);
$('.attachments').append(newSection);
}
$(".attachments section input[type='url']").change(appendSection);
What's odd is this script works just fine if it is on a standalone page, as in the example snippet below. But whenever I call this example snipet using AJAX, suddenly my jQuery script no longer functions. Why would this happen?
// This section handles adding new links to page //
function appendSection() {
$(this).off('change');
const newSection = $(this).closest('section').clone();
newSection.find('input, select').each((i, el) => {
el.value = '';
el.name = el.name.replace(/\[(\d)\]/, (match, p1) => `[${parseInt(p1) + 1}]`);
});
newSection.on('change', appendSection);
$('.attachments').append(newSection);
}
$(".attachments section input[type='url']").change(appendSection);
// This section handles navigation //
function nav(arg) {
var destination = arg.dataset.nav;
var pages = document.querySelectorAll("[data-page]");
var nav = document.querySelectorAll("[data-nav]");
for (i = 0; i < nav.length; i++) { // Remove the class 'active' if it exists
nav[i].classList.remove('active')
}
arg.classList.add('active');
for (i = 0; i < pages.length; i++) { // Hide/show the correct pages
if (pages[i].dataset.page != destination) {
pages[i].style.display = "none";
} else {
if (destination == 'basic') {pages[i].style.display = "flex";}
if (destination != 'basic') {pages[i].style.display = "block";}
}
}
}
.modal {
display: none;
position: fixed;
z-index: 20;
right: 0; top: 0;
width: 100%; height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.6);
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s}
.assignment-window{
display: grid;
position: fixed;
overflow: hidden;
padding: 10px;
padding-bottom: 16px;
box-sizing: border-box;
width: 100vw; height: 70vh;
bottom: 0; left: 0;
border-top-left-radius: 40px;
border-top-right-radius: 40px;
background-color: white;
grid-template-rows: auto 1fr;
grid-template-columns: 0.9fr 2.5fr;
grid-template-areas:
"asstop asstop"
"assnav asscontent"}
/* ----------[ASS TOP]---------- */
.asstop {
grid-area: asstop;
padding: 24px 20px;
box-sizing: border-box;
border-bottom: 2px solid #581F98;}
.asstop .title {
display: flex;
align-items: center;}
.asstop .title input {
flex: 1 1;
font-size: 24px;
border-radius: 8px;
margin-right: 20px;
border: 1px solid lightgray}
.asstop select {
outline: none;
-webkit-appearance: none;
padding: 12px 16px;
font-size: 24px;
box-sizing: border-box;
border-radius: 8px;
border: 1px solid lightgray}
.asstop button {
margin-top: -5px;}
/* ----------[ASS NAV]---------- */
.assnav {
grid-area: assnav;
padding-top: 20px;
padding-right: 10%;
border-right: 1px solid lightgray}
.assnav ul {
margin: 0;
padding: 0;
overflow: hidden;
list-style-type: none}
.assnav li {
display: block;
text-decoration: none;
color: #484848;
font-size: 20px;
padding: 14px 20px;
margin-bottom: 10px;
border-top-right-radius: 40px;
border-bottom-right-radius: 40px;}
.assnav li:hover {background-color: #F2F2F2}
.assnav li.active {background-color: #EEEEEE}
/* ----------[ASS CONTENT]---------- */
.asscontent {
grid-area: asscontent;
display: flex;
flex-direction: column;
padding: 30px;
box-sizing: border-box;
overflow: scroll}
.asscontent input, .asscontent select {
flex: 1;
outline: none;
-webkit-appearance: none;
padding: 8px 16px;
font-size: 18px;
box-sizing: border-box;
border-radius: 8px;
border: 1px solid lightgray}
/* ==== Basic Styling ==== */
.asscontent .basic {
display: flex;
height: 100%;
flex-direction: column}
.asscontent .basic textarea {
flex: 1;
font-size: 18px;
border-radius: 8px;
box-sizing: border-box;}
.asscontent .basic .config {
display: flex;
justify-content: space-between;
padding-top: 20px;}
.asscontent .basic input {text-align: center;}
.asscontent .basic .points {width: 80px;}
/* ==== Attachment Styling ==== */
.asscontent .attachments {display: none}
.asscontent .attachments section {
display: flex;
justify-content: space-between;
padding-bottom: 15px;
margin-bottom: 15px;
border-bottom: 1px solid lightgray}
/* ==== Delete Styling ==== */
.asscontent .advanced {display: none}
/* ==== Delete Styling ==== */
.asscontent .delete {display: none;}
.asscontent .delete ul {margin-bottom: 30px;}
.asscontent .delete li {margin-bottom: 10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class='assignment-window'>
<div class='asstop'>
<div class='title'>
<select name='assEmoji'>
<option >✏️</option>
<option >💻</option>
<option >📚</option>
<option >💯</option>
<option >🧪</option>
</select>
<input name='title' type='text' placeholder='Type assignment title..' value='' required>
<button name='createAss' class='button purple-btn'>Assign Task</button>
</div>
</div>
<div class='assnav'>
<ul>
<li data-nav='basic' onclick='nav(this);' class='active'>Basic Setup</li>
<li data-nav='attachments' onclick='nav(this);'>Attachments</li>
<li data-nav='advanced' onclick='nav(this);'>Advanced Settings</li>
</ul>
</div>
<div class='asscontent'>
<div class='basic' data-page='basic'>
<textarea name='directions' placeholder='Type assignment directions..'></textarea>
<div class='config'>
<section>
<span>Subject: </span>
<select name='subID'>
<option value='1' >Reading</option>
<option value='2' >Social Studies</option>
<option value='3' >Math</option>
<option value='4' >Science</option>
<option value='5' >Writing</option>
</select>
</section>
<section>
<span>Points:</span>
<input name='points' class='points' type='text' value='100'>
</section>
<section>
<span>Due Date:</span>
<input name='due' type='datetime-local' value='2021-09-10T15:00'>
</section>
</div>
</div>
<div class='attachments' data-page='attachments'>
<section>
<div class='displayName'>
<select name='link[0][linkEmoji]'>
<option >📎</option>
<option >🎬</option>
<option >📖</option>
</select>
<input name='link[0][linkTitle]' placeholder='Title of website..' type='text' value=''>
</div>
<div class='url'>
<input name='link[0][linkURL]' placeholder='Insert website URL..' type='url' value=''>
</div>
<div class='visible'>
<span>Visible: <span>
<select name='link[0][linkClass]'>
<option value=''>- All Students -</option><option value='1' >🟣 Reading/Social</option><option value='2' >🔴 Reading/Social</option><option value='3' >🔵 Reading/Social</option><option value='4' >🟢 Reading/Social</option>
</select>
</div>
</section>
</div>
<div class='advanced' data-page='advanced'>
<section>
<span>Visible to students: </span><input name='assigned' type='date' value='2021-09-07'>
</section>
<section>
<span>Submission: </span>
<select name='submitType'>
<option value='scan' >Require students to scan.</option>
<option value='button' >Allow scanning or turn in button.</option>
<option value='button' >Do not allow submissions.</option>
</select>
</section>
<section>
<span>Assignment Type: </span>
<select name='assType'>
<option >Assignment</option>
<option >Assessment</option>
<option >Daily Work</option>
<option >Quiz</option>
<option >Participation</option>
<option >Project</option>
</select>
</section>
</div>
<div class='delete' data-page='delete'>
<p>Deleting the assignment? The following will happen: </p>
<ul>
<li>All recorded scores will be deleted.</li>
<li>Student averages will adjust from the deleted scores.</li>
<li>The assignment will be removed from student view.</li>
<li>This action cannot be undone.</li>
</ul>
<button type='button' class='button grey-btn'>Cancel</button>
<button name='deleteAss' class='button red-btn'>Permanently Delete</button>
</div>
</div>
</div>
For reference, this is what the source code looks like that I am using to call on this page with AJAX:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<a onclick="assignInfo('new')">Launch</a>
<div id="assignModal" class="modal">
<form id="assignInfo" action='assign.int.php' method='POST'></form>
<input form='assignInfo' type='hidden' name='source' value='plan'>
</div>
<script> /* ---- Script to populate Assign modal ---- */
var assignModal = document.getElementById("assignModal");
function assignInfo(str){
assignModal.style.display = "block";
if (str == 'new') {var url = "assignModal.tem.php";}
else {var url = "assignModal.tem.php?assID=" + str;}
fetch(url).then((response) =>response.text()).then((text) => {
var parser = new DOMParser();
var doc = parser.parseFromString(text, "text/html");
var ele = doc.documentElement;
var scripts = ele.getElementsByTagName('script');
for(var script of scripts){
var head = document.getElementsByTagName('head')[0];
var scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.innerText = script.innerText;
head.appendChild(scriptElement);
head.removeChild(scriptElement);
}
document.getElementById("assignInfo").innerHTML=text;
});
}
window.onclick = function(event) { /* Make modal disappear when you click "X" */
if (event.target == assignModal) {
if (confirm("Are you sure? This assignment will not be saved if you exit.")) {
assignModal.style.display = "none";
} else {
assignModal.style.display = "block";
}
}
}
</script>
<script>
// This section handles adding new links to page //
function appendSection() {
$(this).off('change');
const newSection = $(this).closest('section').clone();
newSection.find('input, select').each((i, el) => {
el.value = '';
el.name = el.name.replace(/\[(\d)\]/, (match, p1) => `[${parseInt(p1) + 1}]`);
});
newSection.on('change', appendSection);
$('.attachments').append(newSection);
}
$(".attachments section input[type='url']").change(appendSection);
// This section handles navigation //
function nav(arg) {
var destination = arg.dataset.nav;
var pages = document.querySelectorAll("[data-page]");
var nav = document.querySelectorAll("[data-nav]");
for (i = 0; i < nav.length; i++) { // Remove the class 'active' if it exists
nav[i].classList.remove('active')
}
arg.classList.add('active');
for (i = 0; i < pages.length; i++) { // Hide/show the correct pages
if (pages[i].dataset.page != destination) {
pages[i].style.display = "none";
} else {
if (destination == 'basic') {pages[i].style.display = "flex";}
if (destination != 'basic') {pages[i].style.display = "block";}
}
}
}
</script>
I'm not entirely sure why this would not work whenever I use ajax

Related

How to add CSS after click through javascript and remove it if not clicked

I have encountered a problem with javascript clicking to change CSS!
I hope that the outer frame and text of the clicked option can be thickened after clicking, but the ones that are not selected should not be thickened! I
have tried several ways of writing, but I still don't know how To complete this requirement, I hope to get everyone's help, thank you.
let plan = document.querySelector('.plan');
let price = document.querySelector('.price');
let item = document.querySelectorAll('.item');
for (var i = 0; i < item.length; i++) {
item[i].addEventListener('click', showplan, false);
}
function showplan(e) {
//Originally intended to increase this way, but it seems that it can't be written like this
// e.target.closesst('li').classList.add('bold')
// e.target.closesst('h2').classList.add('bold')
const planSelected = e.target.closest('li').querySelector('h2');
const priceSelected = e.target.closest('li').querySelector('p');
plan.textContent = planSelected.textContent;
price.textContent = priceSelected.textContent;
}
#charset "UTF-8";
.product_list {
display: flex;
}
.product_list .item {
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
padding: 20px;
margin: 20px;
}
.product_list .item h2 {
margin-bottom: 16px;
}
.product_list .item:hover {
border: 1px solid #222;
}
.show {
border: 2px solid blue;
padding: 20px;
}
.bold {
border: 3px solid;
font-weight: 900;
}
<ul class="product_list">
<li class="item">
<h2>coke</h2>
<p>$100</p>
</li>
<li class="item">
<h2>beef</h2>
<p>$600</p>
</li>
</ul>
<h2 class="show">Your food of choice is <span class="plan"></span>The total price is<span class="price"></span></h2>
You need to toggle the class, you can do that by removing it from every item and only setting it to the selected one:
item.forEach(el => el.classList.remove('active'))
e.currentTarget.classList.add('active')
Also you have a CSS specificity issue:
when using only .bold, the border would be overriden by .product_list .item
Note, try using currentTarget
const plan = document.querySelector('.plan');
const price = document.querySelector('.price');
const item = document.querySelectorAll('.item');
function showplan(e) {
const target = e.currentTarget;
const closestLi = target.closest('li');
const planSelected = closestLi.querySelector('h2');
const priceSelected = closestLi.querySelector('p');
item.forEach(el => el.classList.remove('active'))
target.classList.add('active')
plan.textContent = planSelected.textContent;
price.textContent = priceSelected.textContent;
}
item.forEach(el => el.addEventListener('click', showplan));
#charset "UTF-8";
.product_list {
display: flex;
}
.product_list .item {
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
padding: 20px;
margin: 20px;
}
.product_list .item h2 {
margin-bottom: 16px;
}
.product_list .item:hover,
{
border: 1px solid #222;
}
.product_list .active {
border: 3px solid red;
font-weight: 900;
color: red;
}
.show {
border: 2px solid blue;
padding: 20px;
}
<ul class="product_list">
<li class="item">
<h2>coke</h2>
<p>$100</p>
</li>
<li class="item">
<h2>beef</h2>
<p>$600</p>
</li>
</ul>
<h2 class="show">Your food of choice is <span class="plan"></span>The total price is<span class="price"></span></h2>
How to add CSS after click through javascript and remove it if not clicked?
Suppose we have a class"item",we want change "h1"
add class:
e.currentTarget.classList.add('item')
remove class:
e.currentTarget.classList.remove('item')
toggle class:
e.currentTarget.classList.toggle('item')
toggle means:
(If h1 has this class,remove,if not,add)
With jQuery, two :radios and their corresponding labels:
var $plan = $('.plan');
var $price = $('.price');
var $item = $('.item');
$('.item').on('click', showplan);
function showplan(e) {
const plan = $(this).find('h2').text();
const price = $(this).find('p').text();
$plan.text(plan);
$price.text(price);
}
#charset "UTF-8";
.product_list {
display: flex;
}
.product_list .item {
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
padding: 20px;
margin: 20px;
cursor: pointer;
}
.product_list input {
display: none;
}
.product_list .item h2 {
margin-bottom: 16px;
}
.product_list .item:hover {
border: 1px solid #222;
}
.show {
border: 2px solid blue;
padding: 20px;
}
.product_list input:checked + label {
outline: 2px solid black; /* Prevent jumping. */
border: 1px solid black;
font-weight: 900;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product_list">
<input type="radio" name="product" id="coke">
<label class="item" for="coke">
<h2>coke</h2>
<p>$100</p>
</label>
<input type="radio" name="product" id="beef">
<label class="item" for="beef">
<h2>beef</h2>
<p>$600</p>
</label>
</div>
<h2 class="show">Your food of choice is <span class="plan">?</span>. The total price is <span class="price">?</span>.</h2>

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>

Item list container problem in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to arrange the list in such a way that the items only allow to grow the container from the bottom and make scroll bar appear.
CODE : https://codepen.io/Redd_1/pen/qBZWJQG
You can simple set height on ul and set overflow-y: auto to make sure that newly added items are staying within the ul and not moving the whole container.
Demo
//Add item to list
var form = document.getElementById('addForm');
var itemList = document.getElementById('items');
form.addEventListener('submit', addItem);
function addItem(e) {
e.preventDefault();
//User input
var newItem = document.getElementById('item').value;
document.getElementById('item').value = ''
if (newItem == '') {
alert('Please enter some value.')
} else {
//Adding values to the list
var li = document.createElement('li');
li.className = 'list-group-item';
li.appendChild(document.createTextNode(newItem));
//Add a delete button
var deletebtn = document.createElement('button');
deletebtn.className = 'btn';
deletebtn.appendChild(document.createTextNode('X'));
//Append button and li to the ul
li.appendChild(deletebtn);
itemList.appendChild(li);
}
}
//Remove item from list
itemList.addEventListener('click', removeItem);
function removeItem(e) {
if (e.target.classList.contains('btn')) {
if (confirm('Are you sure you want to delete the item?')) {
var li = e.target.parentElement;
itemList.removeChild(li);
}
}
}
//Search items
var filter = document.getElementById('filter');
filter.addEventListener('keyup', filterItems);
function filterItems(e) {
var text = e.target.value.toLowerCase();
var items = itemList.getElementsByTagName('li');
Array.from(items).forEach(function(item) {
var itemName = item.firstChild.textContent;
if (itemName.toLowerCase().indexOf(text) != -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
})
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Montserrat;
}
header {
background-color: green;
color: white;
margin: 0;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.container {
padding: 20px;
position: fixed;
width: 500px;
left: 50%;
top: 55%;
transform: translate(-50%, -50%);
line-height: 40px;
border: 1px solid black;
border-radius: 10px;
}
ul {
overflow-y: auto;
list-style: none;
padding: 10px;
height: 10em;
}
.list-group-item {
border: 1px solid grey;
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px;
}
.btn {
background-color: red;
color: white;
border: none;
border-radius: 5px;
padding: 6px;
}
.sbtn {
color: white;
background-color: rgb(46, 46, 46);
text-transform: uppercase;
cursor: pointer;
border: none;
padding: 8px;
}
.sbtn:hover {
background-color: black;
}
button {
float: right;
}
input[type=text] {
padding: 5px;
}
<!DOCTYPE html>
<html>
<body>
<link rel="stylesheet" href="itemApp.css">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#300;400;500;600;700&display=swap" rel="stylesheet">
<header>
<h1>Item lister</h1>
<input type="text" class="search-bar" placeholder="Search items..." id="filter">
</header>
<div class="container">
<h3>Add items</h3>
<form id="addForm" name="myForm">
<input type="text" id="item" name="textField">
<input type="submit" class="sbtn" value="submit">
</form>
<h3>Items</h3>
<ul id="items">
<li class="list-group-item">Item 1 <button class=btn>X</button> </li>
<li class="list-group-item">Item 2 <button class=btn>X</button> </li>
<li class="list-group-item">Item 3 <button class=btn>X</button> </li>
<li class="list-group-item">Item 4 <button class=btn>X</button> </li>
</ul>
</div>
<script src="itemApp.js"></script>
</body>
</html>

How to print out dynamic items from array to the DOM

I am stuck in a logical problem.
I have an array where i am stacking items with array.push() where came up from a user's Input.
Problem is now:
How can i print these items to the DOM? ATM i am doing this,
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
return incomeArr;
}
}
Creating a associative array in the getInput();
First attempt to print this data into the DOM looked like this:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
for (var i = 0; i < expenseArr.length; i++) {
incomeItemSpan;
incomeList.append(incomeItemSpan);
}
}
My problem here is that my forLoop index condition is messing up because of the "everytime function call" the value which is printed out will be printed twice in the next function call of this. the index start again at 0 and even with a out of function loop counter this will not work.
[![gave-input][1]][1]
So the next attempt was:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
}
i tried it with a forEach and the problem here is, i have absolutely no idea how to print out the incomeItemSpan without a innerHTML. I want a list of items in the DOM which are stacked from top down, every line is a new item from the array like i would use item.append(), but HTML wont work in a append().
How can i do this?
/* TODO:
- Add Eventlistener for Submit a +/- Value
- if + {add 1. into INCOME section} + Set INCOME in header to the amount
of all incomes added
if - {same like if+ just for -}
- create a update DOM function to update the visualisation of the calculations
- INCOME AND EXPENSES should be a Array
- add a prototype function to remove entrys from INCOME and EXPENSES, use
indexOf to get the index item and remove with array.splice().
- calc every expense with INCOME to get a % value of how much this entry is
% related to the max INCOME
*/
// VARS:
let addType = document.querySelector('.add__type');
let description = document.querySelector('.add__description');
let addValue = document.querySelector('.add__value');
let incomeArr = [];
let expenseArr = [];
// EVENTLISTENER Constructor:
function EventListner(selector, listner, fnt) {
this.selector = selector;
this.listner = listner;
this.fnt = fnt;
document.querySelector(selector).addEventListener(listner, fnt);
};
// getInput VALUES FROM USER Constructor:
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return incomeArr;
}
// SAVE IN EXPENSE IF "-" IS CHOOSEN
if (addType.value == 'exp') {
let op = expenseArr['operator'] = operator;
let des = expenseArr['description'] = description;
let val = expenseArr['value'] = value;
expenseArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return expenseArr;
}
};
// STUCK AS FUCK!
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
// for (var i = 0; i < incomeArr.length; i++) {
// console.log([i]);
// incomeItemSpan;
// incomeList.append(incomeItemSpan);
// }
// console.log(incomeItemSpan);
//
// incomeList.append(expenseArr);
// incomeArr.toString();
// expenseArr.toString();
// incomeList.innerHTML = incomeItemSpan;
};
const main = (function() {
// EVENTLISTENERS
const clickListener = new EventListner('.add__btn', 'click', () => {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
getInput(addType.value, description.value, addValue.value);
});
const enterKeyListener = new EventListner('.add__value', 'keypress', (e) => {
let testArray = [];
for (var i = 0; i < testArray.length; i++) {
testArray[i] = [i];
console.log(testArray[i]);
}
testArray.push('item');
if (e.keyCode == 13) {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
// ON ENTER SAVE VALUES IN AN ARRAY
// IF PLUS INTO incomeArr, ON MINUS INTO expenseArr
// getInput(addType.value, description.value, addValue.value);
printToDOM(getInput(addType.value, description.value, addValue.value));
}
});
}());
//
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right { float: right; }
.red { color: #FF5049 !important; }
.red-focus:focus { border: 1px solid #FF5049 !important; }
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description { width: 400px;}
.add__value { width: 100px;}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active { transform: translateY(2px); }
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus { outline: none; }
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title { color: #28B9B5; }
.expenses__title { color: #FF5049; }
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child { border-top: 1px solid #e7e7e7; }
.item:nth-child(even) { background-color: #f7f7f7; }
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus { outline: none; }
.item__delete--btn:active { transform: translateY(2px); }
.item:hover .item__delete--btn { display: block; }
.item:hover .item__value { transform: translateX(-20px); }
.item:hover .item__percentage { transform: translateX(-20px); }
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage { box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1); }
.unpaid:hover .item__description { font-weight: 900; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 0</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 0</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 0</div>
<div class="budget__expenses--percentage">0%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!-- <div class="item clearfix" id="income-0">
<div class="item__description"></div>
<div class="right clearfix">
<div class="item__value"></div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div> -->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Is that exactly what you're looking for?
const arr = new Array();
function addList() {
const el = document.querySelector("input[name=user]")
const val = el.value
arr.push(val);
el.value = null;
return false;
}
function showList() {
for (let i = 0; i < arr.length; i++) {
const listElement = document.createElement("li");
listElement.textContent = arr[i]
document.body.appendChild(listElement);
}
}
<form onsubmit="return addList()">
<input type="text" name="user">
<button>Add list item</button>
</form><br>
<button class="showList" onclick="showList()">Show list</button>
<ul class="list"></ul>
For creating a list of items, create a ordered/unordered list then append each item to this list in forEach and finally set the html to ordered//unordered list.
Example:
var ol=$('<ol></ol>');
incomeArr.forEach(() => {
ol.append($('<li></li>').text(`${item.description}: ${item.value}`));
});
$('#display').html(ol);

How to make my own select

I wish to make my own select.
Actually my select looks like this :
JS Fiddle
and is it coded like this :
<p>Title</p>
<form>
<input type="color" onchange="colorisPanneau(value);pageSuivante();" name="coloris_panneau" list="liste_color3" id="coloris_panneau" value="#C5B9A9" class="formc" style="height:24px;width:202px;">
<datalist id="liste_color3">
<option value="#FFFFFF">
<option value="#999999">
<option value="#000000">
<option value="#582810">
</datalist>
</form>
And i want to make it look like that :
How can i do this ?
What do i need to do to be able to personalize the interface in my combobox ?
Where can i find documentation to be able to do so ?
Thank you very much :)
The datalist cannot be modified with css, even if you could with some css-magic, you could never get multiple items inside of the datalist options. The only solution is to create a select box from scratch.
I was bored so I made you something you can start with:
$('html').on("click", function(e) {
$('.color-picker').removeClass('open');
});
$(document).on("click", ".color-value", function(e) {
e.stopPropagation();
if ($('.color-picker').hasClass('open')) {
$('.color-picker').removeClass('open');
} else {
$('.color-picker').addClass('open');
}
});
$(document).on("click", ".list-item", function() {
var color = $(this).data('color');
$('#color-input').val(color);
$('.color-value').html($(this).html());
//This is now the value of your hidden input field
$('#value').html(color);
});
* {
box-sizing: border-box;
}
.color-picker {
height: 30px;
width: 150px;
overflow: hidden;
color: #666;
background: #FFF;
}
.open {
overflow: visible;
;
}
.list {
border: 1px solid #CCC;
border-top: none;
background: #FFF;
}
.list-item {
padding: 5px;
cursor: pointer;
}
.list-item:hover {
background: #f1f1f1;
}
.list-item>span {
display: inline-block;
vertical-align: middle;
height: 20px;
line-height: 20px;
}
.list-item>span:first-child {
width: 20px;
margin-right: 5px;
}
.color-value {
height: 30px;
line-height: 30px;
padding: 0 5px;
width: 100%;
cursor: pointer;
border: 1px solid #CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="color-picker">
<input id="color-input" type="hidden" name="coloris_panneau" value="" />
<div class="color-value list-item">Select your color</div>
<div class="list">
<div class="list-item" data-color="#edae0e">
<span style="background:#edae0e;"></span>
<span>Yellow</span>
</div>
<div class="list-item" data-color="#ff0000">
<span style="background:#ff0000;"></span>
<span>Red</span>
</div>
<div class="list-item" data-color="#336699">
<span style="background:#336699;"></span>
<span>Blue</span>
</div>
</div>
</div>

Categories

Resources