Element edit button should only edit "that" element, instead is updating all - javascript

So I am trying to make an edit function for a favorites bar. Editing one box is okay, but when I try to edit a different box, all the boxes that I clicked on previously gets edited as well. Here is a jsfiddle with the complete code: https://jsfiddle.net/1exrf9h8/1/
I am trying to understand why my editFavorite function is updating multiple boxes and not just one.
function clickEdit(input, title, url, plus, editIcon, anchorEdit, editBtn)
{
let i = editIcon.length - 1;
editIcon[i].addEventListener("click", function(event){
input.style.display = "block";
title.value = plus[i + 1].textContent;
url.value = anchorEdit[i].href;
console.log(i);
console.log(anchorEdit[i]);
editFavorite(anchorEdit[i], url, title, input, editBtn);
});
}
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
});
}

There is a few problems in your logic, architecture and use of the event handler, Let's give it a shot in a more OOP way so you can actually make it to work and understand what is going on.
Every single favorite is an object by itself, that can spawn and update itself.
function favorite(newTitle, newUrl) {
this.element = container.appendChild(document.createElement("div"));
this.title = this.element.appendChild(document.createElement("h2"));
this.url = this.element.appendChild(document.createElement("h2"));
this.update = (newTitle, newUrl) => {
this.title.textContent = newTitle;
this.url.textContent = newUrl;
}
this.createButton = () => {
button = this.element.appendChild(document.createElement("button"));
button.append("Edit");
button.addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
this.update(titleInput, urlInput);
})
}
this.update(newTitle, newUrl);
this.createButton();
}
Then let's have a simple form where we can take inputs, using the same for editing, and creating a new favorites.
<input id="title" type="text" name="title" placeholder="Title">
<input id="url" type="text" name="url" placeholder="Url">
<button id="submit">Create New</button>
Now the actual submit logic.
document.getElementById("submit").addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
if (!titleInput.length || !urlInput.length) return;
let newFavorite = new favorite(titleInput, urlInput);
container.appendChild(newFavorite.element);
});
https://jsfiddle.net/p50L27us/48/

The problem is caused by editFavorite function. when you call editFavorite function automatically starts new listener. Evey click start new one.
The solution is " ,{once : true} "
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
},{once : true});
}

Related

How can i add or update products and prices in my list?

Pretty new to javascript, i want to add and update my list but it doesn't work.
I tried adding following code but it didn't work
Product.prototype.addProduct = function() {
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent= this.naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent= this.prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function() {
return this.naam + "(€ " + this.prijs +")";
}
This is the document i want wish would work propperly
<!DOCTYPE html>
<html>
<head>
<script src="oefwinkel.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10);
VulLijst();
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VulLijst() {
var elol = document.getElementById("lijst");
var producten = winkel.getProducten("</li><li>");
if (producten.length > 0) {
elol.innerHTML = "<li>" + producten + "</li>";
} else {
elol.innerHTML = "";
}
}
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
VulLijst();
}
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
</script>
</head>
<body>
<div><label for="txtNaam">Naam:</label>
<input type="text" id="txtNaam" /></div>
<div><label for="txtPrijs">Prijs:</label>
<input type="number" id="txtPrijs" /></div>
<input type="button" id="btn" value="Toevoegen/Updaten" />
<ol id="lijst">
</ol>
</body>
</html>
There is no list output how do i correct this?..
I really can't find the solution, what did i miss.. huh?
You had a few things missing,
The HTML code.
The winkel object was undefined.
The VulLijst function was doing nothing... because addProduct was taking care of this already.
You are relying on the instance fields (this.naam and this.prijs), but what you want to do is pass in method parameters (external variables).
As for updating, you will need to store a list of Products, clear the child elements of lijst, and re-add the items that represent the list.
Note: One thing I am confused about is why you named your class—that represents a list—Product, when it should really be an Inventory that allows you to ADD Product objects.
Code
// Uncaught ReferenceError: winkel is not defined
var winkel = new Product();
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
Product.prototype.addProduct = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
console.log(naam, prijs);
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent = naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent = prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
return naam + " (€ " + prijs + ")";
}
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10); // Why are you adding a product to a product?
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
}
label { font-weight: bold; }
<label>Product</label>
<input id="txtNaam" value="Something" />
<input id="txtPrijs"value="1.99" />
<button id="btn">Add</button>
<br/>
<ul id="lijst"></ul>
Explained
I will openly admit, I'm not 100% sure what you're trying to do, I assume that's due to a language barrier my side though, I'm not sure of the natural language that you use on a daily basis, i.e. some of the variable names seem unclear to me, but that's my problem, not yours! :)
Anyway, I used some guess work to figure out what you're trying to achieve, and I assumed that you're simply trying to have some sort of product list where each product has a name and a price attached to it?
You want to be able to add a product to the list, based on two input fields, then some button to add to/update that product list.
I've broken up the code into a couple of simple functions, with this solution you can add/remove as many functions, classes or whatever you want. In this answer you can clearly see that there's some render function, and some onUpdate function, I just went with these generic names for the sake of simplicity.
If you have any issues with this solution, please provide as much feedback as possible! I hope that it's been of some help one way or another.
// A simple product list.
const ProductList = () => {
const products = [];
let el = null;
// What you wish to return, aka an object...
return {
addProduct: (name, price) => {
products.push({
name: name,
price: price
});
onUpdate();
render(el, products);
},
setRoot: root => {
el = root;
},
// removeFromList, etc...
};
};
// A simple on update function.
const onUpdate = () => {
console.clear();
console.log('Update!');
};
// A 'simple' render function.
const render = (el, products) => {
if (el == null) return;
const template = obj => `<li>${obj.name} €${obj.price}</li>`;
let html = '';
products.forEach(product => html += template(product));
el.innerHTML = html;
};
// A function to dispatch some event(s).
const dispatchEvents = products => {
const btn = document.getElementById("btn");
const price = document.getElementById("price");
const name = document.getElementById("name");
// Just an example.
const isValid = () => {
if (price.value != '' && name.value != '') return true;
return false;
};
// Handle the on click event.
btn.onclick = () => {
if (isValid()) {
products.addProduct(name.value, price.value);
name.value = '';
price.value = '';
}
};
};
// A simple dom ready function.
const ready = () => {
const products = ProductList();
products.setRoot(document.getElementById("productList"));
products.addProduct('Demo', 10);
products.addProduct('Other', 19.99);
dispatchEvents(products);
};
document.addEventListener("DOMContentLoaded", ready);
<div>
<label for="name">name:</label>
<input type="text" id="name" />
</div>
<div>
<label for="price">Prijs:</label>
<input type="number" id="price" />
</div>
<input type="button" id="btn" value="Update" />
<ol id="productList">
</ol>

Unable to set the onclick property of a button

I have a button calling a js function. Everything in the function runs but at the end I try to set the onclick value for the button and nothing happens. The catch block doesn't even generate an error
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
I have also tried setting the onclick value these ways
nextButton.onclick = function () { generateCategories(); };
nextButton.onclick = generateCategories;
the tvalue variable is set like this:
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value;
Other test outputs have shown that this retrieves the value no problem
The relevant HTML:
<form id='fieldsets' action="../scripts/reportParse.php">
<fieldset>
<legend> Select Report Type </legend>
<select id="type" name="type">
<option value="trend"> Waitlists over Time </option>
<option value="stats"> Region Statistics </option>
</select>
</fieldset>
<button id="next" onclick="generateRegions()"> Next </button>
I've been trying solutions based on the following page:
Change onclick action with a Javascript function
and w3schools.com
Thanks for any help. I've been hung up on this for a little bit now
Edit: I've tried useing event listeners based on a comment below and am now getting the error "i is not defined'. which seems odd since i is not referred too inside the try block.
The whole function in case i've missed something stupid:
function generateRegions(){
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value; // The value of the selected option
var names = ["Downtown", "Glenmore", "Mission", "Rutland"];
var regions = document.createElement("FIELDSET");
regions.setAttribute("id","Region");
var temp = document.createElement("LEGEND");
temp.innerHTML = "Select Region:";
regions.appendChild(temp); //creating the fieldset div and assigning its legend
for(var i = 0; i < 4; i++){
var templ = document.createElement("LABEL");
var str1 = "chk";
var str2 = i.toString();
var id = str1.concat(str2); //creating a dynamic ID so each checkbox can be referred to individually
templ.setAttribute("for",id);
temp = document.createElement("INPUT"); //creating the checkbox and assigning its values
temp.setAttribute("type","checkbox");
temp.setAttribute("name","region");
temp.setAttribute("value",names[i]);
temp.setAttribute("id",id);
regions.appendChild(templ);
templ.innerText = names[i]+':'; //creating and placing the label, then placing its checkbox
regions.appendChild(temp);
}
document.getElementById("fieldsets").appendChild(regions); //adding the fieldset to the overall form
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
//document.getElementById("demo").innerHTML = tvalue; //checking that the type variable is properly found
}
Try adding an event listener to your code so the JavaScript is separated from the HTML markup. Like so:
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.addEventListener("click",generateLocations()) ;
}
else if (tvalue == "stats"){
nextButton.addEventListener("click",generaCategories()) ;
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
You can test if the event listener is working by adding a console log on the functions you are executing.
Source: https://www.w3schools.com/js/js_htmldom_eventlistener.asp

Displaying Counter on The Actual HTML Button

I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE

HTML5 Javascript . how to Save Textarea input then loading it via buttons

I have a project I'm working on where there's a "Save" button that saves the user's data to localStorage and there's a "Load" button that loads a user's saved data from localStorage. However, it's not working. Can someone please help me fix this problem?
HTML:
<textarea rows="10" cols="50" id="text"></textarea>
<br/><button id="save">Save</button>
<button id="load">Load</button>
JavaScript:
function doSave(){
var txt = text.value;
localStorage.storedText= txt;
}
function doLoad(){
text.value = localStorage.storedText;
}
window.onload = function(){
saveButton = document.getElementById("save");
saveButton.onclick = doSave();
loadButton = document.getElementById("load");
loadButton.onclick = doLoad();
textarea = document.getElementById("text");
};
You're using localStorage incorrectly:
function doSave(){
//Set the item in doSave()
//localStorage.setItem("text", text.value);
}
function doLoad(){
//Get the item in doLoad()
//text.value = localStorage.getItem("text");
}
Also, read Quentin's answer: Don't call doSave() and doLoad() when setting the onclick event:
//When the window loads...
window.onload = function(){
saveButton = document.getElementById("save");
saveButton.onclick = doSave;
loadButton = document.getElementById("load");
loadButton.onclick = doLoad;
textarea = document.getElementById("text");
};
Here's the "fiddle": http://jsfiddle.net/NobleMushtak/JNKaU/
You have to assign functions to onclick properties. You are calling doSave and doLoad and assigning their return values. Since those functions do not have return statements, they return undefined.
Remove the (). Don't call them immediately.

Check if two elements have been clicked, and a value has been entered in a textbox in Javascript

Here's a demo of what I'm talking about - http://jsfiddle.net/MatthewKosloski/qLpT9/
I want to execute code if "Foo" has been clicked, and a number has been entered in the input.. and if "send" has been clicked.
<h1>Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="send">Send</button>
I'm pretty sure I'm overthinking this, I'd appreciate the help on such a concise question.
try this one: jfiddle link
var send = document.getElementById("send");
var h1 = document.getElementsByTagName("h1");
var foo_clicked = 0;
h1[0].onclick = function(){foo_clicked += 1; };
send.onclick = function(){
if(document.getElementById("amount").value !='' && foo_clicked >0 )
alert ('poor rating');
};
As per your statement & taking some assumptions, try this way:
(This executes function twice - When there is a change of text or a click of the button).
HTML:
<h1 id="">Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="sendBtn">send</button>
JS:
document.getElementById("amount").addEventListener("change",poorRatingCalculation);
document.getElementById("sendBtn").addEventListener("click",poorRatingCalculation);
function poorRatingCalculation() {
var rating = document.getElementById("amount").value;
if(rating=="poor") alert("Poor Service");
}
DEMO: http://jsfiddle.net/wTqEv/
A better, self contained example:
http://jsfiddle.net/qLpT9/7/
(function()
{
var clicked = false;
var header = document.getElementById("header");
var amount = document.getElementById("amount");
var send = document.getElementById("send");
header.addEventListener("click", function()
{
clicked = true;
});
send.addEventListener("click", function()
{
if(!clicked)
{
return
}
// Foo has been clicked
var value = amount.value;
console.log(value;)
});
})();
Is this what you were looking for?
http://jsfiddle.net/qLpT9/5/
function poorRatingCalculation(){
if(myInput.value) {
alert(myInput.value);
}
}
var foo = document.getElementById("foo"),
myInput = document.getElementById("amount");
foo.addEventListener("click", poorRatingCalculation, false)

Categories