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
}
})
Related
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.
I have code :
To search a single string and return whole string.
$(document).ready(function() {
$('button').click(function (){
var search = $('#input').val();
var str = $('#file').html();
var output=str.match(search );
document.getElementById("result").innerHTML = output;
if (search.value.length > 0) {
$(".oh").show().filter(function () {
return $('#input').find('li').text().toLowerCase().indexOf($("search").val().toLowerCase()) == -1;
}).hide();
}
else {
$(".oh").show();
document.getElementById( 'oh' ).style.display = 'block';
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="searchbox.js"></script>
</head>
<body>
<input type="text" id="input">
<button>solve</button>
<p id="result"></p>
<div id="file"class="oh"style="display:none;">
<li>beatiful</li>
<li>happy sunday</li><li>good morning</li><li>good evening</li><li>oh my god</li>I like u</li><li>wonderful day</li>
<li>good aftnoon</li>
</div>
</body>
</html>
For example:
`input = good
output = good morning,
good night,
good noon`
`input = morning,
output = good morning`
Its like a search box inside html
Please help me with any suggestion or correct my code its more helpful for me i have use jquery and index() are using but its not work
Check this, i have updated your markup little bit and changed the code to work:
$(document).ready(function() {
$('button').click(function() {
var search = $('#input').val(); // get the search term
var $lis = $('#file li'); // all the existing li items to filter/search
var $resUl = $('#result ul'); // the ul to show results
var o = $lis.map(function() { // map will let you loop through list items
if (this.textContent.indexOf(search) != -1) { // check if the current li in the iteration has the search term
return $(this).clone(); // if yes then return a copy of it.
}
}).get(); // .get() will create an array when used with .map()
$resUl.empty(); // always clear the result ul
$.each(o, function(i, item) { // loop through the array created via filter
$resUl.append(item).find('li').fadeIn(); // here append them as lis are hidden so fade them in the view to show.
});
});
});
#file li {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<input type="text" id="input">
<button>solve</button>
<div id="result">
<ul></ul>
</div>
<ul id="file">
<li>beatiful</li>
<li>happy sunday</li>
<li>good morning</li>
<li>good evening</li>
<li>oh my god</li>
<li>I like u</li>
<li>wonderful day</li>
<li>good aftnoon</li>
</ul>
$(document).ready(function() {
$('button').click(function (){
var searchval = $('#input').val();
var str = $('#file').html();
var rep2 = str.split('</li>');
var rep3 = rep2.filter(function(item){
if(item.search(searchval) !=-1){
return item;
}
})
document.getElementById("result").innerHTML = rep3;
});
});
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("");
}
Can someone tell me what the best way to achieve the same thing seen here with this js:
function ContactController($scope) {
$scope.contacts = ["hi#me.no", "hi#you.com"];
$scope.addMail = function() {
if(this.mailAdress) {
$scope.contacts.push($scope.mailAdress);
$scope.mailAdress = "";
}
};
}
without the use of Angular. I am just trying to learn how save user input to the DOM using javascript. Thanks!
One way of doing the same is
var contacts = ["hi#me.no", "hi#you.com"],
ul = document.querySelectorAll('.email-list')[0];
// Iterate over the contacts and append it to the ul
for (var i = 0; i < contacts.length; i++) {
addEmailToContacts(contacts[i]);
}
function addEmailToContacts(contact) {
var li = document.createElement('li');
li.innerHTML = contact;
ul.appendChild(li);
};
// Click event for the submit
document.querySelector('#submit').addEventListener('click', function(e) {
e.preventDefault();
// Get the value
var value = document.querySelectorAll('input[type="mail"]')[0].value;
if (value) {
addEmailToContacts(value);
}
})
Check Codepen
You can use form element, input type="email" element with required attribute, onsubmit event, event.preventDefault(), Array.prototype.push() , Array.prototype.forEach(), .innerHTML
var contacts = ["hi#me.no", "hi#you.com"],
div = document.getElementById("update");
function updateContacts() {
div.innerHTML = "";
contacts.forEach(function(address) {
div.innerHTML += address + "<br>"
})
}
updateContacts();
document.forms[0].onsubmit = function(event) {
event.preventDefault();
// user input to update `contacts` array
contacts.push(this["input"].value);
// display updated `contacts` array
updateContacts();
}
<div id="update">
</div>
<form>
<input name="input" type="email" required />
<input type="submit" />
</form>
I apologize for posting this question, I'm just learning JavaScript and have tried using the information from other posts but just cannot get my code to work. The object is to create an li tag and insert list items to this newly created tag, then assign an event handler to remove an item if the user clicks on it.
I have the list populating and can remove an item if I hardcode it but cannot for the life of me figure out how to assign the value of the item being clicked on to the removeItem function. I am also trying to clear the list when an item is entered but keep getting the error "Object doesn't support property or method 'reset'".
If someone could point me in the right direction I would appreciate it.
thanks!
<!doctype html>
<html lang="en">
<head>
<title> Add and delete items Objective </title>
<meta charset="utf-8">
<style>
p {
font-style: italic;
}
li:hover {
cursor: pointer;
}
</style>
<script>
// your code here!
var itemList = [];
window.onload = init;
function init() {
var addButton = document.getElementById("submitButton");
addButton.onclick = addItem;
//var itemList = document.getElementById("list");
var itemsList = document.getElementsByTagName("li");
itemsList.onclick = removeItem;
}
function addItem() {
var newItem = document.getElementById("item").value;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(newItem));
ul.appendChild(li);
itemList.push(newItem);
document.getElementById("item").reset();
}
function removeItem() {
var editList = document.getElementsByTagName("li");
// var editList = document.getElementsById("list");
for (var i = 0; i < editList.length; i++) {
var item = editList[i];
if(editList.options[i].selected) {
editList.removeChild(editList.childNodes[i]);
}
}
}
</script>
</head>
<body>
<form>
<label form="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="list">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
</html>
Why not set the value of the item input to an empty string rather than using reset?
document.getElementById("item").value = "";
As for removing the list items...
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].addEventListener("click", removeItem);
}
you can only reset forms, so you have to select the form and then reset will work. f.e. with:
document.forms[0].reset()
your code is adding the eventhandler to all existing li-Elements, if you create some new li-Elements later, you have to add the eventhandler to it manually. f.e. in your addItem-Function with:
li.onclick = removeItem;
after pushing the new Item
in your removeItem-Function you have access on the clicked Element via this, so you can remove only this Element with:
this.remove()
You could change your addItem() and removeItem() functions :
function addItem() {
var newItem = document.getElementById("item").value;
$('#list').append("<li id='" + newItem + "' onclick='removeItem(this)'>" + newItem + "</li>");
}
function removeItem(id) {
$(id).remove();
}