How to dynamically update div numbering with js - javascript

I have an input in which, through the onclick function, new inputs are added via innerhtml, but when I delete 1 object, it goes out of the list. How to do it please help
var x = 0;
function addInputIIN() {
if (x < 4 ){
var profile = document.getElementById('formDriverInputs');
var div = document.createElement('div');
idX = 'driverIdInput' + [x + 1]
NameX = 'driverNameInput' + [x + 1]
div.id = 'inputDriverBlock' + ++x;
const numDriver = x + 1
div.innerHTML = '<div class="inputContainer d-flex align-items-start"><div class="input-group- prepend"><div class="input-group-text">'+numDriver+'</div></div><input type="text" class="form-control form__iin mb-3 position-relative" id='+ idX +' name='+ NameX +' aria-describedby="driver" placeholder="Введите иин" ><img src="https://w7.pngwing.com/pngs/185/104/png-transparent-emblem-icon-icons-matt-minus-symbol.png" alt="" class="form__img-add" alt="" onclick="delInputIIN()"> <a href=""> </div>';
console.log(div)
profile.appendChild(div);
console.log(x)
}else{
var toastBody = document.querySelector('.toast-body')
toastBody.innerHTML = 'Не может быть больше 5 водителей на 1 машину'
BsAlert.show();
}
}
function delInputIIN() {
var inputs = document.querySelectorAll('.inputIcon')
var div = document.getElementById('input' + x);
var parent = event.target.parentNode.parentNode
parent.remove();
--x
console.log(x)
}
.form__img-add{
width:32px;
}
<div class="form-group text-start" id="formDriverInputs">
<div id="inputDriverBlock0">
<div class="inputContainer">
<div class="input-group-prepend">
<div class="input-group-text">1</div>
<input type="text" id="driverIdInput0" name="driverNameInput0"placeholder="Введите иин" '> <img src="https://image.emojipng.com/610/1872610.jpg" alt="" class="form__img-add" onclick="addInputIIN()">
</div>
</div>
</div>
</div>
How to make sure that when deleting all the numbering goes in order from 1 to 5

If you delegate and clone you have a much easier time
Note how I hide the first minus
window.addEventListener("DOMContentLoaded", () => {
const container = document.getElementById("formDriverInputs");
const toastBody = document.querySelector(".toast-body")
const tmp = document.getElementById("tmp")
const maxEntries = 5;
const renum = () => {
container.querySelectorAll(".input-group-text").forEach((txt,i) => txt.textContent = (i+1));
}
const addContent = () => {
container.append(tmp.content.cloneNode(true));
renum();
}
container.addEventListener("click", (e) => {
const tgt = e.target;
if (tgt.matches(".form__img-remove")) {
tgt.closest(".inputDriverBlock").remove();
renum();
return;
}
if (tgt.matches(".form__img-add")) {
if (container.children.length === maxEntries) {
toastBody.innerHTML = 'Не может быть больше 5 водителей на 1 машину'
// BsAlert.show(); // I do not have that plugin
return;
}
addContent();
}
});
addContent(); // add the first
});
.form__img-add {
width: 32px;
height: 22px;
}
.form__img-remove {
height: 22px;
}
#formDriverInputs > div:nth-child(1) .form__img-remove { display: none }
<div class="form-group text-start" id="formDriverInputs"></div>
<div class="toast-body"></div>
<template id="tmp">
<div class="inputDriverBlock">
<div class="inputContainer d-flex align-items-start">
<div class="input-group-prepend">
<div class="input-group-text"></div>
<input type="text" class="form-control form__iin mb-3 position-relative" name="" aria-describedby="driver" placeholder="Введите иин" /> <img src="https://image.emojipng.com/610/1872610.jpg" alt="" class="form__img-add">
<img src="https://w7.pngwing.com/pngs/185/104/png-transparent-emblem-icon-icons-matt-minus-symbol.png" alt="" class="form__img-remove" />
</div>
</div>
</div>
</template>

Related

Next/prev button for modal with Javascript

I have been trying to make modal for a custom site I'm building. Everything seemed to go fine. It displayed whichever picture I clicked on and "previous" button works as intended. However, there seems to be a problem with "next" button because it behaves differently depending on which picture I'm currently on. Sometimes it jumps by few indexes forward or even backwards. Some insight would be appreciated. Thanks in advance. Here is a code HTML:
<div id="modalcontainer" class="displaynone">
<h4>
<span id="close">X</span>
</h4>
<img src="" alt="" id="modalcontent">
<div class="buttoncontainer">
<div class="previous">
<span id="prev"><</span>
</div>
<div class="next">
<span id="next">></span>
</div>
</div>
</div>
<div id="imgcontainer">
<img src="images/1.JPG" alt="">
<img src="images/2.JPG" alt="">
<img src="images/3.JPG" alt="">
<img src="images/4.JPG" alt="">
<img src="images/8.png" alt="">
<img src="images/9.jpg" alt="">
<img src="images/10.jpg" alt="">
</div>
And JS:
const modalContainer = document.getElementById("modalcontainer");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
const closeModal = document.getElementById("close");
const modalContent = document.getElementById("modalcontent");
const imgContainer = document.getElementById("imgcontainer");
let containerImages = imgContainer.querySelectorAll("img");
let imgIndex = 0;
containerImages.forEach(function(img){
img.setAttribute("data-index", imgIndex++);
img.addEventListener("click", () => {
if(modalContainer.classList.contains("displaynone")){
modalContainer.classList.remove("displaynone");
modalContainer.classList.add("displaymodal");
modalContent.src = img.src;
};
imgIndex = img.dataset.index;
console.log(imgIndex);
});
});
closeModal.addEventListener("click", () => {
if(modalContainer.classList.contains("displaymodal")){
modalContainer.classList.remove("displaymodal");
modalContainer.classList.add("displaynone");
}
imgIndex = 0;
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % containerImages.length;
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
prevButton.addEventListener("click", () => {
imgIndex = (imgIndex -= 1);
if (imgIndex < 0) {
imgIndex = containerImages.length - 1;
console.log(imgIndex);
};
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
I dummied up some objects to get it to run and your previous/next button code seems to work. It there some other code that might be involved? Something modifying the number of images in the imageContainer?
const prevButton = document.querySelector("#prev");
const nextButton = document.querySelector("#next");
let images = document.querySelectorAll("img");
let imgIndex = 0;
images.forEach((img) =>
img.addEventListener("click", () => {
imgIndex = parseInt(img.dataset.index);
setSelected();
})
);
setSelected();
prevButton.addEventListener("click", () => {
imgIndex = imgIndex -= 1;
if (imgIndex < 0) imgIndex = images.length - 1;
setSelected();
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % images.length;
setSelected();
});
function setSelected() {
images.forEach((img) => img.classList.remove("selected"));
images[imgIndex].classList.add("selected");
}
img {
display: inline-block;
border: 2px solid transparent;
}
.selected {
border: 2px solid red;
}
<div id="imageContainer">
<img src="https://picsum.photos/100?random=1" data-index="0">
<img src="https://picsum.photos/100?random=2" data-index="1">
<img src="https://picsum.photos/100?random=3" data-index="2">
<img src="https://picsum.photos/100?random=4" data-index="3">
</div>
<div>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>

How do I make a function that reset the game on click

I am working on a rock paper scissor game. I'm very new to javascript and only know the basics. The code is a little sloppy. What I want is to be able to continue playing the game after a choice is selected. For example, right now if I click rock, the CPU will randomize a result, but then if I click on paper, the result will stay on the screen and the new result will overlap the old one.
I was thinking of adding another condition to the if statements. Also, I was thinking of adding another function to the return of the if statement that might reset it.
html
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
js
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
function cpuChoice() {
const rand = Math.random()
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
} else {
cpuScissors.style.display = 'inline-block'
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice))
css
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
position: absolute;
height: 11rem;
}
Firstly, you need to remove position: absolute; for img which was causing the overlapping.
Secondly, each time you call cpuChoice(), you need to hide the previous element before showing the current element.
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let currentItem;
function cpuChoice() {
const rand = Math.random();
if (currentItem) {
currentItem.style.display = 'none';
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block';
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block';
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block';
currentItem = cpuScissors;
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice));
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
height: 5rem;
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
You don't need all those IDs and Classes.
Use Indexes!
Using indexes you can also retrieve the winner
See this answer: https://stackoverflow.com/a/53983473/383904
const moves = ["Rock", "Paper", "Scissors"],
messages = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
score = [0, 0, 0], // [PL, AI, draw]
ELS = sel => document.querySelectorAll(sel),
EL_result = ELS("#result")[0],
EL_PLScore = ELS("#PLScore")[0],
EL_AIScore = ELS("#AIScore")[0],
ELS_ai = ELS(".ai");
function game() {
const PL = +this.dataset.user; // Get played index as integer
const AI = ~~(Math.random() * 3); // All you need: 0, 1, 2
const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw
score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
EL_result.innerHTML = `You: ${moves[PL]}, AI: ${moves[AI]}, ${messages[result]}`;
EL_PLScore.textContent = score[0];
EL_AIScore.textContent = score[1];
ELS_ai.forEach(el => el.classList.remove('inline-block')); // Hide all
ELS_ai[AI].classList.add('inline-block'); // Show one
}
// EVENTS:
document.querySelectorAll("[data-user]").forEach(el => el.addEventListener("click", game));
.ai {
display: none;
}
.ai.inline-block {
display: inline-block
}
<div class="main-container">
<div class="score">
<span>You: <span id="PLScore">0</span></span>
<span>Computer: <span id="AIScore">0</span></span>
</div>
<div class="user-choice">
<img data-user="0" src="//placehold.it/50x50/888?text=ROCK">
<img data-user="1" src="//placehold.it/50x50/eee?text=PAPER">
<img data-user="2" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div class="cpu-result">
<img class="ai" src="//placehold.it/50x50/888?text=ROCK">
<img class="ai" src="//placehold.it/50x50/eee?text=PAPER">
<img class="ai" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div id="result"></div>
</div>

Javascript sending wrong get request

So basically, I have an image upload page where users can upload images.I use laravel for the backend.It hasn't been working since and the server kept returning errors.So I chnaged the post request to GET and I found out that instead of the script sendind something like http://localhost:8000/upload?title='whatever'&body='theimageselected.jpg'
Of course,the title and body values are variables.They will be different according to what the user wants to uploaad..
It sends this:
http://localhost:8000/upload?[object%20Object]&_=1558376643031
Why?
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>CodePen - Image Upload With Live Preview using FormData</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<style>
.container {
padding-top: 3%;
}
.hide-element {
display: none;
}
.glyphicon-remove-circle {
float: right;
font-size: 2em;
cursor: pointer;
}
/*
* http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
*/
.btn-file {
position: relative;
overflow: hidden;
/*box-shadow: 10px 10px 5px #888888;*/
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
.alert,
.well {
box-shadow: 10px 10px 5px;
-moz-box-shadow: 10px 10px 5px;
-webkit-box-shadow: 10px 10px 5px;
}
#uploadDataInfo p {
margin-left: 2%;
margin-top: 3%;
font-size: 1.2em;
}
.media-left #edit {
z-index: 1000;
cursor: pointer;
}
.thumbnail #edit {
position: absolute;
display: inline;
z-index: 1000;
top: 1px;
right: 15px;
cursor: pointer;
}
.thumbnail #delete {
position: absolute;
display: inline;
z-index: 1000;
margin-top: 4%;
top: 20px;
right: 15px;
cursor: pointer;
}
.caption input[type="text"] {
/*width: 80%;*/
}
.thumbnail .fa-check-circle {
color: #006dcc;
*color: #0044cc;
}
.thumbnail .fa-times-circle {
color: #E74C3C;
}
.modal-header .close {
float: right !important;
margin-right: -30px !important;
margin-top: -25px !important;
background-color: white !important;
border-radius: 15px !important;
width: 30px !important;
height: 30px !important;
opacity: 1 !important;
}
.modal-header {
padding: 0px;
min-height: 0px;
}
.modal-dialog {
top: 50px;
}
.media-left img {
cursor: pointer;
}
.label-tags {
font-size: 16px;
padding: 1%;
color: black;
background-color: white;
border: 1px solid blue;
border-radius: 4px;
margin: 3px;
}
.label-tags i {
cursor: pointer;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div id="individualImagePreview" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<img src="" alt="default image" class="img-responsive" id="individualPreview" />
</div>
<div class="modal-footer" id="displayTags">
<div class="pull-left">
</div>
</div>
</div>
</div>
</div>
<div id="progressModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<div id="ajaxLoad">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemax="100" id="progressIndicator" style="">
<span class="sr-only">45% Complete</span>
</div>
</div>
<i class="fa fa-cog fa-spin fa-4x"></i> </div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="alert hide-element" role="alert" id="errorMessaage"></div>
<div class="alert hide-element" role="alert" id="file-error-message">
<span class='glyphicon glyphicon-remove-circle'></span>
<p></p>
</div>
<form class="well" id="imagesUploadForm">
<label for="file">Select files to upload</label>
<br />
<span class="btn btn-primary btn-file">
Browse <input type="file" multiple="multiple" accept="image/*" id="uploadImages" /></span>
<p class="help-block">
Only jpg,jpeg,png file with maximum size of 2 MB is allowed.
</p>
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-lg btn-primary disabled" value="Preview" name="imagesUpload" id="imagesUpload">Preview</button>
</form>
<div id="uploadDataInfo" class="alert hide-element">
<a href="#" class="close" data-dismiss="alert" aria-label="close">
<i class="fa fa-times"></i>
</a>
<p class="" id="toManyFilesUploaded"></p>
<p class="" id="filesCount"></p>
<p class="" id="filesSupported"></p>
<p class="" id="filesUnsupported"></p>
</div>
<div class="hide-element" id="previewImages">
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="0" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags:max of 3 tags.comma seperated </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo0">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete0">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="1" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo1">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete1">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="2" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo2">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete2">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="3" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label>
<input type="text" class="form-control" name="description" value="" /></p>
<p><label for="caption">Caption: </label>
<input type="text" class="form-control" name="caption" value="" /></p>
<p><label for="tags">Tags: </label>
<input type="text" class="form-control" name="tags" value="" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo3">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete3">Delete</a>
</div>
</div>
<button class="btn btn-primary pull-left" id="sendImagesToServer" data-toggle="modal" data-target="#progressModal" data-keyboard="false" data-backdrop="static">Update & Preview</button>
</div>
<br /><br />
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner" role="listbox" id="previewItems">
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script id="rendered-js">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip({
html: true });
$('.media').addClass('hide-element');
$('#imagesUploadForm').submit(function (evt) {
evt.preventDefault();
});
$('#edit').click(function () {
console.log('click detected inside circl-o of edit');
$('#edit').toggleClass('fa-circle-o').toggleClass('fa-check-circle');
if ($('#edit').hasClass('fa-check-circle')) {
$('#captionForImage').toggleClass('hide-element');
} else {
$('#captionForImage').toggleClass('hide-element');
}
});
$('#delete').click(function () {
console.log('click detected inside circl-o of delete');
$('#delete').toggleClass('fa-circle-o').toggleClass('fa-times-circle');
});
//namespace variable to determine whether to continue or not
var proceed = true;
//Ensure that FILE API is supported by the browser to proceed
if (proceed) {
var input = "";
var formData = new FormData();
$('input[type=file]').on("change", function (e) {
var counter = 0;
var modalPreviewItems = "";
input = this.files;
$($(this)[0].files).each(function (i, file) {
formData.append("file[]", file);
});
$('#previewImages').removeClass('hide-element');
$('#imagesUpload').removeClass('disabled');
var successUpload = 0;
var failedUpload = 0;
var extraFiles = 2;
var size = input.length;
$(input).each(function () {
var reader = new FileReader();
var uploadImage = this;
console.log(this);
reader.readAsArrayBuffer(this);
reader.onload = function (e) {
var magicNumbers = validateImage.magicNumbersForExtension(e);
var fileSize = validateImage.isUploadedFileSizeValid(uploadImage);
var extension = validateImage.uploadFileExtension(uploadImage);
var isValidImage = validateImage.validateExtensionToMagicNumbers(magicNumbers);
var thumbnail = validateImage.generateThumbnail(uploadImage);
if (fileSize && isValidImage) {
$('#' + counter).parents('.media').removeClass('hide-element');
$('#' + counter).attr('src', thumbnail).height('200');
$('#uploadDataInfo').removeClass('hide-element').addClass('alert-success');
successUpload++;
modalPreviewItems += carouselInsideModal.createItemsForSlider(thumbnail, counter);
} else {
$('#uploadDataInfo').removeClass('hide-element alert-success').addClass('alert-warning');
failedUpload++;
}
counter++;
if (counter === size) {
$('#myCarousel').append(carouselInsideModal.createIndicators(successUpload, "myCarousel"));
$('#previewItems').append(modalPreviewItems);
$('#previewItems .item').first().addClass('active');
$('#carouselIndicators > li').first().addClass('active');
$('#myCarousel').carousel({
interval: 2000,
cycle: true });
if (size > 4) {
$('#toManyFilesUploaded').html("Only files displayed below will be uploaded");
extraFiles = size - 4;
}
$('#filesCount').html(successUpload + " files are ready to upload");
if (failedUpload !== 0 || extraFiles !== 0) {
failedUpload === 0 ? "" : failedUpload;
extraFiles === 0 ? "" : extraFiles;
$('#filesUnsupported').html(failedUpload + extraFiles + " files were not selected for upload");
}
}
};
});
});
$(document).on('click', '.glyphicon-remove-circle', function () {
$('#file-error-message').addClass('hide-element');
});
$("body").on("click", ".media-object", function () {
var image = $(this).attr('src');
$("#individualPreview").attr('src', image);
var tags = [];
var displayTagsWithFormat = "";
$(this).parents('.media').find('input[type="text"]').each(function () {
if ($(this).attr('name') === 'tags') {
tags = $(this).val().split(",");
$.each(tags, function (index) {
displayTagsWithFormat += "<span class = 'label-tags label'>#" + tags[index] + " <i class='fa fa-times'></i></span>";
});
$("#displayTags").html("<div class='pull-left'>" + displayTagsWithFormat + "</div>");
//console.log(tags);
}
});
});
var toBeDeleted = [];
var eachImageValues = [];
$('.media').each(function (index) {
var imagePresent = "";
$("body").on("click", "#delete" + index, function () {
imagePresent = $("#" + index).attr('src');
$("#undo" + index).removeClass('hide-element');
$("#" + index).attr('src', './img/200x200.gif');
$("#delete" + index).addClass('hide-element');
toBeDeleted.push(index);
//console.log(toBeDeleted);
$("#delete" + index).parent().find('input[type="text"]').each(function () {
var attribute = $(this).attr('name');
var attributeValue = $(this).val();
eachImageValues[attribute + index] = attributeValue;
//console.log(eachImageValues);
});
//console.log(toBeDeleted.length);
if (toBeDeleted.length === 4) {
$('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');
} else {
$('#sendImagesToServer').prop('disabled', false).html('Update & Preview');
}
$("#delete" + index).parent().find('input[type="text"]').prop('disabled', true).addClass('disabled');
});
$("body").on("click", "#undo" + index, function () {
$("#" + index).attr('src', imagePresent);
$("#undo" + index).addClass('hide-element');
$("#delete" + index).removeClass('hide-element');
var indexToDelete = toBeDeleted.indexOf(index);
if (indexToDelete > -1) {
toBeDeleted.splice(indexToDelete, 1);
// console.log(toBeDeleted);
$("#delete" + index).parent().find('input[type="text"]').prop('disabled', false).removeClass('disabled');
}
if (toBeDeleted.length === 4) {
$('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');
} else {
$('#sendImagesToServer').prop('disabled', false).html('Update & Preview');
}
});
});
$('body').on("click", "#sendImagesToServer", function () {
var counter = 0;
var imageData = "";
var consolidatedData = [];
$('.media').each(function () {
var description = "";
var caption = "";
var tags = "";
$('.media').find('input[type="text"]').each(function (index) {
if ((index === 0 || index <= 11) && counter <= 11) {
counter++;
var attributeName = "";
var attributeValue = "";
attributeName = $(this).attr('name');
attributeValue = $(this).val();
switch (attributeName) {
case "title":
title = attributeName;
// console.log(description);
break;
case "caption":
body = attributeName;
// console.log(caption);
break;
case "tags":
tags =attributeName;
// console.log(tags);
break;
default:
break;}
if (counter % 3 === 0) {
imageData = new imageInformation(description, caption, tags);
consolidatedData.push(imageData);
//JSON.stringify(consolidatedData);
//console.log(toBeDeleted);
}
}
});
});
imageData = new deleteList(toBeDeleted);
consolidatedData.push(imageData);
var sendData = JSON.stringify(consolidatedData);
formData.append("important", sendData);
$.ajax({
type: 'GET',
url: '/upload',
xhr: function () {
var customXhr = $.ajaxSettings.xhr();
if (customXhr.upload) {
customXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return customXhr;
},
data: {title:"test",body:"body"},
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('#ajaxLoad').addClass('hide-element');
$('#successResponse').html(data.message);
console.log(data.message + " inside success function");
},
error: function (data) {
$('#successResponse').html(data.responseJSON.message).addClass('label label-danger').css({
'font-size': '18px' });
console.log(data.responseJSON.message + " inside error function");
} });
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('#progressIndicator').css({
'width': e.loaded });
}
};
//
//console.log(JSON.stringify(consolidatedData));
});
function imageInformation(description, caption, tags) {
this.description = description;
this.title = caption;
this.tags = tags;
this.type = "image";
};
function deleteList(toBeDeleted) {
this.toBeDeleted = toBeDeleted;
};
var validateImage = {
magicNumbersForExtension: function (event) {
var headerArray = new Uint8Array(event.target.result).subarray(0, 4);
var magicNumber = "";
for (var counter = 0; counter < headerArray.length; counter++) {if (window.CP.shouldStopExecution(0)) break;
magicNumber += headerArray[counter].toString(16);
}window.CP.exitedLoop(0);
return magicNumber;
},
isUploadedFileSizeValid: function (fileUploaded) {
var fileSize = fileUploaded.size;
var maximumSize = 2097125;
var isValid = "";
if (fileSize <= maximumSize) {
isValid = true;
} else {
isValid = false;
}
return isValid;
},
uploadFileExtension: function (fileUploaded) {
var fileExtension = "";
var imageType = "";
imageType = fileUploaded.type.toLowerCase();
fileExtension = imageType.substr(imageType.lastIndexOf('/') + 1);
return fileExtension;
},
validateExtensionToMagicNumbers: function (magicNumbers) {
var properExtension = "";
if (magicNumbers.toLowerCase() === "ffd8ffe0" || magicNumbers.toLowerCase() === "ffd8ffe1" ||
magicNumbers.toLowerCase() === "ffd8ffe8" ||
magicNumbers.toLocaleLowerCase() === "89504e47") {
properExtension = true;
} else {
properExtension = false;
}
return properExtension;
},
generateThumbnail: function (uploadImage) {
if (window.URL)
imageSrc = window.URL.createObjectURL(uploadImage);else
imageSrc = window.webkitURL.createObjectURL(uploadImage);
return imageSrc;
} };
var carouselInsideModal = {
createIndicators: function (carouselLength, dataTarget) {
var carouselIndicators = '<ol class = "carousel-indicators" id="carouselIndicators">';
for (var counter = 0; counter < carouselLength; counter++) {if (window.CP.shouldStopExecution(1)) break;
carouselIndicators += '<li data-target = "#' + dataTarget + '"data-slide-to="' + counter + '"></li>';
}window.CP.exitedLoop(1);
carouselIndicators += "</ol>";
return carouselIndicators;
},
createItemsForSlider: function (imgSrc, counter) {
var item = '<div class = "item">' + '<img src="' + imgSrc + '" id="preview' + counter + '" /></div>';
return item;
} };
}
});
//# sourceURL=pen.js
</script>
<script>
$('.laravel-like').on('click', function(){
if($(this).hasClass('disabled'))
return false;
var item_id = $(this).data('item-id');
var vote = $(this).data('vote');
$.ajax({
method: "post",
url: "/",
data: {item_id: item_id, vote: vote},
dataType: "json"
})
.done(function(msg){
if(msg.flag == 1){
if(msg.vote == 1){
$('#'+item_id+'-like').removeClass('outline');
$('#'+item_id+'-dislike').addClass('outline');
}
else if(msg.vote == -1){
$('#'+item_id+'-dislike').removeClass('outline');
$('#'+item_id+'-like').addClass('outline');
}
else if(msg.vote == 0){
$('#'+item_id+'-like').addClass('outline');
$('#'+item_id+'-dislike').addClass('outline');
}
$('#'+item_id+'-total-like').text(msg.totalLike == null ? 0 : msg.totalLike);
$('#'+item_id+'-total-dislike').text(msg.totalDislike == null ? 0 : msg.totalDislike);
}
})
.fail(function(msg){
alert(msg);
});
});
$(document).on('click', '.reply-button', function(){
if($(this).hasClass("disabled"))
return false;
var toggle = $(this).data('toggle');
$("#"+toggle).fadeToggle('normal');
});
$(document).on('submit', '.laravelComment-form', function(){
var thisForm = $(this);
var parent = $(this).data('parent');
var item_id = $(this).data('item');
var comment = $('textarea#'+parent+'-textarea').val();
$.ajax({
method: "get",
url: "/laravellikecomment/comment/add",
data: {parent: parent, comment: comment, item_id: item_id},
dataType: "json"
})
.done(function(msg){
$(thisForm).toggle('normal');
var newComment = '<div class="comment" id="comment-'+msg.id+'" style="display: initial;"><a class="avatar"><img src="'+msg.userPic+'"></a><div class="content"><a class="author">'+msg.userName+'</a><div class="metadata"><span class="date">Today at 5:42PM</span></div><div class="text">'+msg.comment+'</div><div class="actions"><a class="reply reply-button" data-toggle="'+msg.id+'-reply-form">Reply</a></div><form class="ui laravelComment-form form" id="'+msg.id+'-reply-form" data-parent="'+msg.id+'" data-item="'+item_id+'" style="display: none;"><div class="field"><textarea id="'+msg.id+'-textarea" rows="2"></textarea></div><input type="submit" class="ui basic small submit button" value="Reply"></form></div><div class="ui threaded comments" id="'+item_id+'-comment-'+msg.id+'"></div></div>';
$('#'+item_id+'-comment-'+parent).prepend(newComment);
$('textarea#'+parent+'-textarea').val('');
})
.fail(function(msg){
alert(msg);
});
return false;
});
$(document).on('click', '#showComment', function(){
var show = $(this).data("show-comment");
$('.show-'+$(this).data("item-id")+'-'+show).fadeIn('normal');
$(this).data("show-comment", show+1);
$(this).text("Show more");
});
$(document).on('click', '#write-comment', function(){
$($(this).data("form")).show();
});
</script>
</body>
</html>
you can try
data: JSON.stringify({
title: "Test",
body: "test"
}),

jQuery - Run change function on load

In the wishlist ui function, I append items to the wishlist by checking the .wish-btn. I want to simulate items already added to the list so I need to run the function on load so that all of the items have been checked.
How do I run the function on load so that all of the items are:
Already checked
Appended to the list
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
</div>
`
Follow charlietfl's answer, then you will get an error:
TypeError: getWish is not a function
Then you have to move your change event handler to the bottom below getWish and updateWish function, because they need to be declared first to be used by the event handler.
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
// Move this block to the bottom after you have defined all functions
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
}).prop('checked', true).change();
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
</div>
You can trigger a change right after you create a change event listener by chaining change() with no arguments to it.
Using prop('checked', true) will check them and you can chain that as well
$(selector).on('change', function(evt){
// do stuff when change occurs
// now check it and trigger change
}).prop('checked', true).change()

Use a javascript function in a generated html code

I'm programming a simple html form with generated code from javascript.
When i run the code in HTML itself it works, but when i put the script in a separate file, it doesn't work anymore. I tried to change the onclick event, generate the code in html, giving my elements a class and add a eventlistner to that, but nothing worked.
this is a part of my javascript code
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
EDIT
the full javascript code
(function ($) {
$( document ).ready( function() {
/* VIEWPORT FIXES (http://timkadlec.com/2013/01/windows-phone-8-and-device-width/) */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style');
msViewportStyle.appendChild(
document.createTextNode(
'#-ms-viewport{width:auto!important}'
)
);
document.querySelector('head').appendChild(msViewportStyle);
}
document.getElementById("factuurFormSend").onclick = addLine;
var omschList=[];
var uurprList=[];
var aantalList=[];
var idlist=["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList]
function addLine(){
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
/*print de lijnen verticaal uit*/
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML=""
var subtotaal=0;
for (var i=0; i<uurprList.length;i++){
var totaal = uurprList[i]*aantalList[i];
subtotaal +=totaal;
var li = document.createElement("LI");
li.innerHTML=totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML=subtotaal;
document.getElementById("btwbedrag").innerHTML=(subtotaal*0.21);
document.getElementById("totaal").innerHTML=(subtotaal*1.21);
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
} );
})(jQuery);
And the HTML code that worked
<body>
<div class="page">
<header class="header">
</header>
<div role="main" class="cf">
<div class="container" id="factuur">
<section id="header">
<div class="col-sm-8">
<h1>Factuur</h1>
</div>
<div class="col-sm-8">Factuur nr. 1</div>
<div class="col-sm-6">
<div>Naam onderneming<br />
Straatnaam nr<br />
Postcode Gemeente<br />
BE 0123 456 789</div>
</div>
<div class="col-sm-6">
<div>Naam Klant<br />
Straatnaam nr<br />
Postcode Gemeente<br />
BE 0123 456 789</div>
</div>
</section>
<section id="content-header">
<div class="col-sm-6">Omschrijving</div>
<div class="col-sm-2">Uurprijs</div>
<div class="col-sm-2">Aantal</div>
<div class="col-sm-2">Totaal</div>
</section>
<section id="content">
<div class="col-sm-6" id="omschrijving"><ul></ul></div>
<div class="col-sm-2" id="uurprijs"><ul></ul></div>
<div class="col-sm-2" id="aantal"><ul></ul></div>
<div class="col-sm-2" id="lijntotaal"><ul></ul></div>
</section>
<section id="totalen">
<div class="col-sm-offset-7 col-sm-3 text-right">Subtotaal</div>
<div class="col-sm-2" id="subtotaal"></div>
<div class="col-sm-offset-7 col-sm-3 text-right">BTW</div>
<div class="col-sm-2" id="btw">21 %</div>
<div class="col-sm-offset-7 col-sm-3 text-right">BTW Bedrag</div>
<div class="col-sm-2" id="btwbedrag"></div>
<div class="col-sm-offset-7 col-sm-3 text-right" style="border-top:1px solid black;">Totaal</div>
<div class="col-sm-2" id="totaal" style="border-top:1px solid black;"></div>
</section>
<section id="factuurknop">
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#factuurModal">
Voeg een factuurlijn toe
</button>
</section>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="factuurModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Voeg een factuur item toe</h4>
</div>
<form>
<div class="modal-body">
<input style="width:30%" type="text" name="formOmschrijving" id="formOmschrijving" placeholder="Omschrijving">
<input style="width:30%" type="text" name="formUurprijs" id="formUurprijs" placeholder="Uurprijs">
<input style="width:30%" type="text" name="formUren" id="formUren" placeholder="uren">
</div>
<div class="modal-footer">
<button type="button" id="factuurFormSend" class="btn btn-primary">Verzenden</button>
</div>
</form>
</div>
</div>
</div>
<script>
document.getElementById("factuurFormSend").onclick = addLine;
var omschList=[];
var uurprList=[];
var aantalList=[];
var idlist=["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList]
function addLine(){
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
/*print de lijnen verticaal uit*/
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML=""
var subtotaal=0;
for (var i=0; i<uurprList.length;i++){
var totaal = uurprList[i]*aantalList[i];
subtotaal +=totaal;
var li = document.createElement("LI");
li.innerHTML=totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML=subtotaal;
document.getElementById("btwbedrag").innerHTML=(subtotaal*0.21);
document.getElementById("totaal").innerHTML=(subtotaal*1.21);
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
} );
</script>
Place your functions in the global scope if you want to assign the click events inline. Not in the load event handler.
Better would be is not to add the click event inline but use event delegation for it. jQuery has great tools for this. Also your code is a weird combination between plain javascript and jQuery functions. It will work, but in my opinion it's better to stay to one style for readability
(function($) {
$(document).ready(function() {
/* VIEWPORT FIXES (http://timkadlec.com/2013/01/windows-phone-8-and-device-width/) */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style');
msViewportStyle.appendChild(
document.createTextNode(
'#-ms-viewport{width:auto!important}'
)
);
document.querySelector('head').appendChild(msViewportStyle);
}
document.getElementById("factuurFormSend").onclick = addLine;
});
function addLine() {
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
})(jQuery);
var omschList = [];
var uurprList = [];
var aantalList = [];
var idlist = ["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList
]
/*print de lijnen verticaal uit*/
function print() {
for (var j = 0; j < 3; j++) {
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML = "";
for (var i = 0; i < omschList.length; i++) {
var li = document.createElement("LI");
if (j == 0) {
li.innerHTML = (idlist[j + 3][i] + "<object align=\"right\" onclick=\"verwijder(" + i + ")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j + 3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML = ""
var subtotaal = 0;
for (var i = 0; i < uurprList.length; i++) {
var totaal = uurprList[i] * aantalList[i];
subtotaal += totaal;
var li = document.createElement("LI");
li.innerHTML = totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML = subtotaal;
document.getElementById("btwbedrag").innerHTML = (subtotaal * 0.21);
document.getElementById("totaal").innerHTML = (subtotaal * 1.21);
}
function verwijder(index) {
for (var i = 0; i < 3; i++) {
idlist[i + 3].splice(index, 1);
}
print();
}
If you want to be able to delete an object on click you could do this with jQuery and event delegation pretty easily.
//Wait till the initial DOM loading is done
$(document).ready(function() {
//Attach an event handler to the click event to the button the adds a new object
$("#addObject").on('click', function() {
$('#staticParent').append("<div class='deletableObject'>deletable on click</div>")
});
//Attach event delegation from the element with id staticParent to place a function on
//the click event of all elements with the class deletableObject inside the element with
//id staticParent. Because it's event delegation it will work also for elements with this
//class the will be added later dynamicly.
$("#staticParent").on('click', '.deletableObject', function() {
$(this).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="staticParent" style="min-height: 100px">
<div class="deletableObject">deletable on click</div>
</div>
<button id="addObject">Add</button>

Categories

Resources