I am trying to add a li element in the below div (Functionality is to upload an attachment)
See below pic 1
My JavaScript functionality of Submit button adds the Li in the div perfectly fine. But, when I refresh the page it's gone.
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<button type="button" id="submit-button" onclick="Submit()">Submit</button>
<div id="collapseThree">
</div>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
const submitBtn = document.getElementById("submit-button");
const slides = [];
var str = '';
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
window.addEventListener('load', (event) => {
console.log(slides)
console.log('The page has fully loaded yo');
// document.getElementById("collapseThree").innerHTML
});
/* window.onload = document.getElementById("slideContainer").innerHTML
*/
function Submit() {
console.log("going in");
document.getElementById("collapseThree").innerHTML += str
}
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
console.log(customTxt.innerHTML)
slides.push(customTxt.innerHTML);
slides.forEach(function(slide) {
str = '<li>' + slide + '</li>';
});
console.log(arr)
console.log(slides)
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
You can use localStorage to save and read data. Simply call
function getSlides() {
var slidesJson = localStorage.getItem('slides') || '[]';
return JSON.parse(slidesJson);
}
to get all current slides and
function setSlides(slides) {
localStorage.setItem('slides', JSON.stringify(slides))
}
to save the current state of the array.
Related
i'm studying JS and at the moment i'm not really good with it. I created a page (a kind of social network) and i need to add an image from an URL when i fill a form. The form has 2 fields: Image title and URL
the initial cards that i have on the page, i handle to insert them from an array. But i can't understand how to add a single photo from a form.
The new photo should appear as first image, the previous 1st image should be at the 2nd place and so on, cards can be deleted when i click on a button but i didn't really got how to do it, and the like buttons should work for every single cards... i've was looking for it on google and i found some stuffs but they didn't work for me.
how can i solve it?
my code:
HTML
<section class="cards" id="cards">
<!-- images will be added here-->
<div class="cards__add-form-overlay">
<form class="cards__add-form">
<button class="cards__add-form-close-icon"></button>
<p class="cards__add-form-text">New place</p>
<input type="text" placeholder="Name" class="cards__add-form-first-field" id="ImageName" value= "">
<input type="text" placeholder="Image URL" class="cards__add-form-second-field" id="URL" value= "">
<button type="submit" class="cards__add-form-submit">create</button>
</form>
</div>
</section>
<template class="elements" id="elements">
<div class="element">
<div class="element__card">
<img class="element__photo" src="" alt="">
<div class="element__button-container">
<button type="button" class="element__trash-button" id="trashbutton">
</div>
<div class="element__text">
<p class="element__place"></p>
<button type="button" class="element__like-button" id="likebutton" onclick="toggle()"></button>
</div>
</div>
</template>
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
JS
// IMAGES //
// description: adding photos in the page from an array with JS //
const initialCards = [
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''}
];
initialCards.forEach(card => cardItem(card));
function cardItem(cardData) {
const container = document.getElementById("cards");
const cardTemplate = document.getElementById("elements").content;
const newCard = cardTemplate.cloneNode(true);
const elementImage = newCard.querySelector('.element__photo');
const elementText = newCard.querySelector('.element__place');
elementImage.src = cardData.link;
elementText.textContent = cardData.name;
container.append(newCard);
}
----- Until here all good
// description: adding popup when clicking on + button, and close with X button //
document.querySelector('.profile__add-button').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'visible';
});
document.querySelector('.cards__add-form-close-icon').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'hidden';
});
document.querySelector('.cards__add-form-submit').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'hidden';
});
document.querySelector('.profile__add-button').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'visible';
});
document.querySelector('.cards__add-form-close-icon').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'hidden';
});
document.querySelector('.cards__add-form-submit').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'hidden';
});
// description: adding photo through popup with 2 fields, name and URL //
const addPhoto = document.querySelector('.cards__add-form');
const imageNameInput = document.querySelector('.cards__add-form-first-field');
const imageUrlInput = document.querySelector('.cards__add-form-first-field');
function handleAddCardFormSubmit(evt) {
evt.preventDefault();
const element = createCard(imageNameInput.value, imageUrlInput.value);
elements.prepend(element);
imageNameInput.value = '';
imageUrlInput.value = '';
closePopup(evt.target.closest('.cards__add-form'));
}
function createCard(name, link) {
const elementTemplate = document.querySelector('#element-template').content;
const element = elementTemplate.querySelector('.element').cloneNode(true);
const elementImage = element.querySelector('.element__photo');
const elementTitle = element.querySelector('.element__place');
elementImage.src = link;
elementTitle.textContent = name;
//like button//
const likeButton = element.querySelector('.element__like-button');
likeButton.addEventListener('click', () => likeButton.classList.toggle('element__like-button_active'));
//delete cards //
element.addEventListener('click', function (evt) {
if (evt.target.classList.contains('element__trash-button')) {
evt.currentTarget.remove();
}
if (evt.target.classList.contains('element__photo')) {
openImagePopup(name, link);
}
});
return element;
}
initialCards.forEach(({name, link}) => elements.append(createCard(name, link)));
with this code, the new image doesn't appear, about like button console says that toogle() is not defined, and delete button don't delete the image but no error in the console
I'm trying to write a CRUD app. I'm having trouble figuring out how to edit and delete individual items. For each item created, I'm making two <a> tags inside of a <span> tag. One for edit and one for delete. But I can't seem to figure out how to make them do what they need to do. At this point they don't do anything because I can't figure out how to access the values correctly.
Note - I'm just beginning to learn jQuery so, any pro tips on that are appreciated.
Here's the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class='form'>
<input id="input" type="text" placeholder="Type here..">
</form>
<h3>Notes</h3>
<ul></ul>
<button id='clear'>Clear All</button>
</div>
<script src="app.js"></script>
</body>
</html>
And the javascript:
const app = {};
app.counter = (function(){
var i = -1;
return function(){
i += 1;
return i;
}
})()
app.create = function(element){
return document.createElement(element);
}
app.select = function(element){
return document.querySelector(element);
}
app.makeList = function(text) {
var i = app.counter();
var li = app.create('li');
var div = app.create('span');
var edit = app.create('a');
var del = app.create('a');
li.textContent = text;
edit.textContent = ' Edit';
edit.href = '#'
del.textContent = ' Delete';
del.href = '#'
div.appendChild(edit);
div.appendChild(del);
li.appendChild(div);
ul.insertBefore(li, ul.childNodes[0])
li.id = 'item' + i;
del.id = 'delete' + i;
edit.id = 'edit' + i;
}
// constants & variables
const ul = app.select('ul')
const input = app.select('input')
var notes;
$(document).ready(function(){
if (localStorage.getItem('notes')) {
notes = JSON.parse(localStorage.getItem('notes'));
} else {
notes = [];
}
localStorage.setItem('notes', JSON.stringify(notes));
// build list items and display them on the page
JSON.parse(localStorage.getItem('notes')).forEach(function(item){
app.makeList(item);
});
// when form is submitted
$('.form').submit(function(e){
e.preventDefault();
if (input.value.length > 0){
notes.push(input.value);
localStorage.setItem('notes', JSON.stringify(notes));
app.makeList(input.value);
input.value = "";
}
})
// clear items on page and from local storage
$('#clear').click(function(){
if (window.confirm('This will clear all items.\nAre you sure you want to do this?')){
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild)
}
}
});
$('ul').on('click', 'li', function(){
console.log(this.textContent) // logs whatever is typed + Edit Delete
})
});
Do something like this.
$("ul").on("click", "li", function(e) {
console.log(this.textContent); // logs whatever is typed + Edit Delete
if(e.target.id === "edit") {
//edit
}
if(e.target.id==="delete") {
//delete
}
});
You are trying to access elements before they are ready that is why you are not able to see anything.
Declare them on global level but assign them value after the document is ready.
var ul;
var input;
var notes;
$(document).ready(function () {
ul = app.select('ul')
input = app.select('input')
...Rest of your code
});
For the Edit and Delete Functionality
As you are appedning IDs in edit and delete button you need to parse that as well
$('ul').on('click', 'li', function (e) {
if (e.target.id.includes('edit')) {
console.log(` item ${e.target.id.split('edit')[1]} needs to be edited.`)
}
if (e.target.id.includes('delete')) {
//delete
}
})
I have a simple text input where users type anything and after sumbitting text appear on a page and stays there, which I done with localStorage, but after refreshing the page only last typed input is showing, Ill post my code to be more specific:
HTML:
<body>
<input id="NewPostField" type="text" value="">
<button onclick="myFunction()">Post</button>
<div id="Posts"></div>
</body>
JavaScript:
function myFunction() {
var NewPostField =
document.getElementById("NewPostField");
var newPost = document.createElement("p");
localStorage.setItem('text',
NewPostField.value);
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
(function() {
const previousText = localStorage.getItem('text');
if (previousText) {
var NewPostField = document.getElementById("NewPostField");
NewPostField.value = previousText;
myFunction();
}
})();
Any help will be great!
It seems that your code is only storing the last value posted.
To store more than one post, one idea is to stringify an array of values to store in localStorage.
Then, parse that stringified value back into an array as needed.
Here's an example:
function getExistingPosts() {
// fetch existing data from localStorage
var existingPosts = localStorage.getItem('text');
try {
// try to parse it
existingPosts = JSON.parse(existingPosts);
} catch (e) {}
// return parsed data or an empty array
return existingPosts || [];
}
function displayPost(post) {
// display a post
var new_post = document.createElement("p");
new_post.innerHTML = post;
posts.appendChild(new_post);
}
function displayExistingPosts() {
// display all existing posts
var existingPosts = getExistingPosts();
posts.innerHTML = '';
inputPost.value = '';
if (existingPosts.length > 0) {
existingPosts.forEach(function(v) {
displayPost(v);
});
inputPost.value = existingPosts.slice(-1)[0];
}
}
function addPost(post) {
// add a post
var existing = getExistingPosts();
existing.push(post);
localStorage.setItem('text', JSON.stringify(existing));
displayPost(post);
}
function clearPosts() {
// clear all posts
localStorage.removeItem('text');
displayExistingPosts();
}
var posts = document.getElementById("posts");
var inputPost = document.getElementById("input_post");
var btnPost = document.getElementById('btn_post');
var btnClear = document.getElementById('btn_clear');
btnPost.addEventListener('click', function() {
addPost(inputPost.value)
});
btnClear.addEventListener('click', clearPosts);
displayExistingPosts();
<input id="input_post" type="text" value="">
<button type="button" id="btn_post">Post</button>
<button type="button" id="btn_clear">Clear</button>
<div id="posts"></div>
Since localStorage isn't supported in StackSnippets, here's a JSFiddle to help demonstrate.
I've made a start to a to do list. I've got it adding an item when you submit an item.
I want to now add local storage when you refresh the page so the items are saved in the browser.
I obviously need to save all the times when the page is refreshed but because my items only update on click I'm not sure how to grab that function data outside the function and save the items.
Any ideas?
Cheers
JS Fiddle:
https://jsfiddle.net/x1bj8mfp/
// When submit item
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
}
You could write the whole array to local storage whenever you add an item:
localStorage.setItem('items', JSON.stringify(items));
Then on page load you would read from local storage the array and assign it back to your variable, or set it to [] (like now), if nothing is in local storage, and then display these items:
var items = JSON.parse(localStorage.getItem('items')) || [];
items.forEach(function (itemValue) {
var listItems = document.createElement('li');
listItems.textContent = itemValue;
listContainer.appendChild(listItems);
});
This updated JSFiddle has that code included.
Of course, you will need some function to delete items as well, otherwise you can only grow your list.
Here's a full solution for you. Note that the code snippet won't work here, due to the cors and sandbox. Just paste it into your code editor.
var submit = document.getElementById('form');
submit.addEventListener('submit', addItem);
var items = [];
var itemValues = document.getElementById('items');
var listContainer = document.createElement('ul');
itemValues.appendChild(listContainer);
//retrieve data after reload
window.onload = function() {
if (localStorage.userData != undefined) {
var userData = JSON.parse(localStorage.getItem('userData'));
for (var i = 0; i < userData.length; i++) {
var listItems = document.createElement('li');
listItems.innerHTML = userData[i];
listContainer.appendChild(listItems);
items = userData;
}
}
}
// Add item
function addItem(e) {
e.preventDefault();
var item = this.querySelector('[name=item]');
var itemValue = item.value;
items.push(itemValue);
item.value = '';
// Output items
var listItems = document.createElement('li');
listItems.innerHTML = itemValue;
listContainer.appendChild(listItems);
localStorage.setItem('userData', JSON.stringify(items));
}
<main>
<form id="form">
<input class="form-input" type="text" name="item" placeholder="Add item">
<input class="btn btn-block" type="submit" value="Submit">
</form>
<div id="items"></div>
<div id="completed"></div>
</main>
Here some helpful small example for local storage
function save() {
var fieldvalue = document.getElementById('save').value;
localStorage.setItem('text', fieldvalue);
}
function load() {
var storedvalue = localStorage.getItem('textfield');
if (storedvalue) {
document.getElementById('textfield').value = storedvalue;
}
}
function remove() {
document.getElementById('textfield').value = '';
localStorage.removeItem('textarea');
}
<body onload="load()">
<input type="textarea" id="textfield">
<input type="button" value="Save" id="save" onclick="save()">
<input type="button" value="remove" id="remove" onclick="clr()">
</body>
<!--save& run this in local to see local storage-->
I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}