Not sure what I am doing wrong here but I am trying to create a simple update/edit function to be able to edit ingredients that exist with the dataset. I am getting the above error when doing so.
Here is my code:
deleteIngredient(){
const ingredientId = this.parentElement.dataset.id
fetch(`${recipeUrl}/${ingredientId}`, {
method: "DELETE"
})
this.parentElement.remove()
}
updateIngredient(){
var editForm = document.getElementById("ingredient-input")
console.log(editForm)
}
editIngredient(){
var editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
editForm.addEventListener("click", updateIngredient)
}
const editBtn = document.createElement('button')
editBtn.addEventListener("click", this.editIngredient)
editBtn.innerText = "Edit"
li.appendChild(editBtn)
ingredientList.appendChild(li)
What am I doing wrong here? This should at least not be throwing this error. Please Help!
Edit: Updated code using onclick got rid of the error!
const editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient" onclick="updateIngredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
//editForm.addEventListener("click", updateIngredient)
}
updateIngredient(){
document.querySelector("data-id")
}
I could still use help with updateIngredient which will take the ingredient and edit it using the edit form. Any other advice would be so appreciated!
Edit 2: Still feeling a bit lost so here is my full Ingredient class and index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/styles.css">
<title>Recipe App</title>
</head>
<body>
<h1>Easy Recipe and Ingredient Saver</h1>
<br>
<h2>Instructions:</h2>
<h3>Enter the name of your recipe below in the top form.</h3>
<h3>After creation add all the ingredients for that recipe separately and hit enter to save to the recipe.</h3>
<div id="container">
<h4>Create a Recipe:</h4>
<form id="recipe-form">
<input type="text" id="recipe-input">
<input type="submit" value="Create Recipe">
</form>
<ul id="recipe-list">
</ul>
</div>
<script src='./src/ingredient.js'></script>
<script src='./src/recipe.js'></script>
<script src='./src/index.js'></script>
</body>
</html>
class Ingredient {
constructor(ingredient) {
this.recipe_id = ingredient.recipe_id
this.name = ingredient.name
this.id = ingredient.id
}
static createIngredient(e){
e.preventDefault()
const ingredientInput = e.target.children[0].value
const ingredientList = e.target.nextElementSibling
const recipeId = e.target.parentElement.dataset.id
Ingredient.submitIngredient(ingredientInput, ingredientList, recipeId)
e.target.reset()
}
renderIngredient(ingredientList){
const li = document.createElement('li')
li.dataset.id = this.recipe_id
li.innerText = this.name
const deleteBtn = document.createElement('button')
deleteBtn.addEventListener("click", this.deleteIngredient)
deleteBtn.innerText = "X"
li.appendChild(deleteBtn)
ingredientList.appendChild(li)
const editBtn = document.createElement('button')
editBtn.addEventListener("click", this.editIngredient)
editBtn.innerText = "Edit"
li.appendChild(editBtn)
ingredientList.appendChild(li)
}
static submitIngredient(ingredient, ingredientList, recipeId){
fetch(ingredientUrl, {
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
name: ingredient,
recipe_id: recipeId
})
}).then(res => res.json())
.then(ingredient => {
let newIngredient = new Ingredient(ingredient)
newIngredient.renderIngredient(ingredientList)
})
}
deleteIngredient(){
const ingredientId = this.parentElement.dataset.id
fetch(`${recipeUrl}/${ingredientId}`, {
method: "DELETE"
})
this.parentElement.remove()
}
editIngredient(){
const editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient" onclick="updateIngredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
//editForm.addEventListener("click", updateIngredient)
}
updateIngredient(){
const ingredientId = this.parentElement.dataset.id
ingredientId.innerText("")
}
}
Related
I have a view which contains a form and looks like this,
<form class="flex-form" id="form" method="">
<div class="form-component">
<label>Type</label>
<input type="text" id="type" name="type">
</div>
<div class="form-component">
<div class="form-component"><label><b>Contents</b></label></div>
<label>Savoury</label><input type="text" name="savoury" id="savoury">
<label>Fillings</label><input type="text" name="fillings" id="fillings">
<label>Amount</label><input type="text" name="amount" id="amount">
<div class="flex-component">
<button class="set-button" type="button" id="set">Set Item</button>
</div>
</div>
<div class="form-component">
<label class="description-label">Description</label>
<textarea class="fixed-textarea" id="description" name="description" cols="15" rows="10"></textarea>
</div>
<div class="form-component">
<label >Unit Price</label>
<input type="text" id="price" name="unit_price">
</div>
<div class="flex-component">
<button class="form-button" type="submit">Add</button>
</div>
</form>
I have a JavaScript that allows me to capture some intermediary information (via the Set Item button) from the form before the form gets submitted (via the Add Button). I want to handle the form's submission from the script since I need to capture the intermediary data.
let collectedItems = [];
let setter = document.getElementById('set');
let form = document.getElementById('form');
setter.addEventListener('click',getSetContent);
function getSetContent() {
let type = document.getElementById('savoury');
let fillings = document.getElementById('fillings');
let amount = document.getElementById('amount');
const content = {
type: type.value,
fillings: fillings.value.split(','),
amount: Number(amount.value)
};
collectedItems.push(content);
clearInputFields([type,fillings,amount]);
}
function clearInputFields(inputFields) {
inputFields.forEach(field => {
field.value = ''
});
console.log(collectedItems);
}
form.addEventListener('submit',submitForm);
function submitForm() {
const type = document.getElementById('type').value;
const desc = document.getElementById('description').value;
const price = Number(document.getElementById('price').value);
const content = collectedItems;
const data = {
type: type,
contents: content,
description: desc,
unit_price: price
};
post('http://localhost:8001/add/box',
{ 'Content-Type': 'application/json' },
JSON.stringify(data)
);
}
function post(endpoint,header,body) {
const response = fetch(endpoint,{ method: 'POST',headers: header,body: body });
response.then(
resp => {
if (resp.ok) {
console.log('form submitted');
} else {
console.log('form not submitted');
}
}
)
}
I then make a POST request using fetch() to an endpoint I have setup in Express which looks like this,
app.post('/add/box',(req,res) => {
const box: any = req.body;
console.log(box);
// DO SOME DB STUFF
res.redirect('/');
});
The form submission works as intended (logs to terminal using nodemon), however I am unable to redirect to the homepage. Instead I stay on the form page after the submission has occurred and I can't figure out why. Any help with this issue is much appreciated.
I'm having trouble figuring out my javascript. The e.preventDefault() is not working. I've tried changing the submit input to a button as well. I know with a form and using rails that it has an automatic rage reload but I thought e.preventDefault was suppose to stop that. Is there some hidden feature in the backend that I need to turn off? I set my project up to be an api by using an api flag. It also has all the right info for cors. My server is showing my data correctly ...it's just the frontend I cant get up.
I'm going to post a sample code I followed.
<html lang="en" dir="ltr">
<head>
<title>Problems</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<script type="application/javascript" src="src/user.js" charset="UTF-8"></script>
<script type="application/javascript" src="src/problem.js" charset="UTF-8"></script>
</head>
<body>
<div class="container" id="container">
<h1>Everyone Has Problems</h1>
<div id="new-user-and-new-problem-container">
<form id="new-user-form">
<label>Your name:</label>
<input type="text" id="new-user-body"/>
<input type="submit"/>
</form>
</div>
</div>
<div id="problems-container" class="problems-container">
</div>
</body>
</html>```
src/user.js
```document.addEventListener('DOMContentLoaded', function(){
User.createUser()
})
class User {
constructor(user){
this.id = user.id
this.name = user.name
this.problems = user.problems
}
static createUser(){
let newUserForm = document.getElementById('new-user-form')
newUserForm.addEventListener('submit', function(e){
e.preventDefault()
console.log(e);
fetch('http://localhost:3000/api/v1/users', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(
{
user: {
name: e.target.children[1].value
}
})
})
.then(resp => {
return resp.json()
})
.then(user => {
let newUser = new User(user)
newUser.displayUser()
})
})
}
displayUser() {
let body = document.getElementById('container')
body.innerHTML = ''
let userGreeting = document.createElement('p')
userGreeting.setAttribute('data-id', this.id)
let id = userGreeting.dataset.id
userGreeting.innerHTML = `<h1>Hey, ${this.name}!</h1>`
body.append(userGreeting)
if (this.problems) {
this.problems.forEach(function(problem){
let newProblem = new Problem(problem)
newProblem.appendProblem()
})
}
Problem.newProblemForm(this.id)
}
}```
src/problem.js
```class Problem {
constructor(problem){
this.id = problem.id
this.name = problem.name
this.description = problem.description
}
static newProblemForm(user_id) {
let body = document.getElementById('container')
let form =
`
<form id="new-problem-form">
<label>What's your problem?:</label>
<input type="text" id="problem-name"/>
<label>Describe it:</label>
<input type="text" id="problem-description"/>
<input type="submit"/>
<h4>Your current problems:</h4>
</form>
`
body.insertAdjacentHTML('beforeend', form)
Problem.postProblem(user_id)
}
//is it appropriate for this to be a static method?
static postProblem(user_id) {
let newForm = document.getElementById('new-problem-form')
newForm.addEventListener('submit', function(e){
e.preventDefault()
fetch('http://localhost:3000/api/v1/problems', {
method: "POST",
headers:{
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(
{
problem: {
name: e.target.children[1].value,
description: e.target.children[3].value,
user_id: user_id
}
}
)
})
.then(resp => resp.json())
.then(json => {
let newProblem = new Problem(json)
newForm.reset()
newProblem.appendProblem()
})
})
}
appendProblem(){
let problems = document.getElementsByClassName('problems-container')
let li = document.createElement('li')
li.setAttribute('data-id', this.id)
li.setAttribute('style', "list-style-type:none")
li.innerHTML = `${this.name} ~~ ${this.description}`
let solveForm = `<button type="button" id="${this.id}" class="solve-problem"> Solve </button>`
li.insertAdjacentHTML('beforeend', solveForm)
problems[0].append(li)
let button = document.getElementById(`${this.id}`)
this.solve(button)
}
solve(button){
button.addEventListener('click', function(e){
e.preventDefault()
fetch(`http://localhost:3000/api/v1/problems/${e.target.parentNode.dataset.id}`, {
method: "DELETE"
})
e.target.parentElement.remove();
})
}
}```
Try not splitting the element up.
document.getElementById('new-problem-form').
addEventListener('submit', function(e){
e.preventDefault()
}
even Jquery
$('#new-problem-form').addEventListener('submit', function(e){
e.preventDefault()
});
The preventDefault is working on the event..
Take this for example:
$('#message').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
This is preventing the enter key from defaulting the submit based on the keydown function. Is this option the actual 'default' you're trying to stop?
When someone write name and click on the search button then I want to show the search result into unordered list from external result.json file.I am just having a issue how to fetch result and show into the list.Please help me. I ll appreciate it.Below is my code.
index.html file
<form method="POST">
<label>Search</label>
<input type="text" id="Search" />
<input type="submit">
</form>
<!-----Show result here-->
<ul>
<li>
</li>
</ul>
<script>
const userAction = async () => {
const response = await fetch('test.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
</script>
result.json file
[
{
"id":1,
"name":"John",
"City":"Melbourne",
"state":"VIC"
}
]
For demonstration it was necessary to replace your source with placeholder.
const list = document.getElementById('list');
const userAction = async (event) => {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
todos.forEach((todo) => {
const li = document.createElement('li');
li.innerHTML = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
});
})
}
<form method="POST" onsubmit="userAction(event);">
<label>Search</label>
<input type="text" id="Search" />
<input type="submit">
</form>
<!-----Show result here-->
<ul id="list"></ul>
Just after the " // do something with myJson"
you can do:
var myListElement = document.getElementById("myList");
myListElement.innerHTML = '<li>Id: '+ item.id +'</li>' + '<li>Name: '+ item.name +'</li>' + '<li> City: '+ item.City +'</li>' + '<li>State: '+ item.state +'</li>';
And Just After the:
You can edit your element like this:
<ul id="myList">
In my search, when I add states such as Michigan or Ohio it returns back National State Parks this part works fine. My problem is that when you just add the State abbreviation it doesn't work so well.
In the API documentation, I can add 'stateCode A comma delimited list of 2 character state codes.' at which I have. In turn it spits out a CURL at which I am not familiar with at all. This is the curl: curl -X GET "https://developer.nps.gov/api/v1/parks?stateCode=AK%2C%20AL%2C%20AR%2C%20AZ%2C%20CA%2C%20CO%2C%20CT%2C%20DC%2C%20DE%2C%20FL%2C%20GA%2C%20HI%2C%20IA%2C%20ID%2C%20IL%2C%20IN%2C%20KS%2C%20KY%2C%20LA%2C%20MA%2C%20MD%2C%20ME%2C%20MI%2C%20MN%2C%20MO%2C%20MS%2C%20MT%2C%20NC%2C%20ND%2C%20NE%2C%20NH%2C%20NJ%2C%20NM%2C%20NV%2C%20NY%2C%20OH%2C%20OK%2C%20OR%2C%20PA%2C%20RI%2C%20SC%2C%20SD%2C%20TN%2C%20TX%2C%20UT%2C%20VA%2C%20VT%2C%20WA%2C%20WI%2C%20WV%2C%20WY&api_key=VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH" -H "accept: application/json"
How can I add this to my javascript to make this work when I just want to put in the 2 character state abbreviation?
"use strict";
const apiKey = "VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH";
const searchURL = "https://api.nps.gov/api/v1/parks";
function formatQueryParams(params) {
const queryItems = Object.keys(params).map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
);
return queryItems.join("&");
}
function displayResults(responseJson) {
// if there are previous results, remove them
console.log(responseJson);
$("#results-list").empty();
// iterate through the items array
for (let i = 0; i < responseJson.data.length; i++) {
// for each park object in the items
//array, add a list item to the results
//list with the park title, description,
//and thumbnail
$("#results-list").append(
`<li><h3>${responseJson.data[i].fullName}</h3>
<p>${responseJson.data[i].description}</p>
<a href='${responseJson.data[i].url}'>${responseJson.data[i].url}</a>
</li>`
);
}
//display the results section
$("#results").removeClass("hidden");
}
function getNationalParksInfo(query, maxResults = 10) {
const params = {
key: apiKey,
q: query,
limit: maxResults - 1
};
const queryString = formatQueryParams(params);
const url = searchURL + "?" + queryString;
console.log(url);
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err => {
$("#js-error-message").text(`Something went wrong: ${err.message}`);
});
}
function watchForm() {
$("form").submit(event => {
event.preventDefault();
const searchTerm = $("#js-search-term").val();
const maxResults = $("#js-max-results").val();
getNationalParksInfo(searchTerm, maxResults);
});
}
$(watchForm);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>National Parks by Location</title>
<link rel="stylesheet" href="style.css" />
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"
></script>
</head>
<body>
<div class="container">
<h1>Your National Parks</h1>
<form id="js-form">
<label for="search-term">Search term</label>
<input type="text" name="search-term" id="js-search-term" required />
<label for="max-results">Maximum results to return</label>
<input
type="number"
name="max-results"
id="js-max-results"
value="10"
/>
<input type="submit" value="Go!" />
</form>
<p id="js-error-message" class="error-message"></p>
<section id="results" class="hidden">
<h2>Search results</h2>
<ul id="results-list"></ul>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
The desired outcome is for me to either type the full state name of the state abbreviation and I get the same search results.
Some context: I'm trying to finish building out the delete functionality of my minimal note-taking app.
Every time I create a new note, it will appear at the end of my list of notes. However, if I try to delete the newly created note, it won't work. I have to refresh the page and try again for it to work.
I keep getting these two errors:
"Uncaught TypeError: Cannot read property 'parentNode' of null at HTMLUListElement."
"DELETE http://localhost:3000/api/v1/notes/undefined 404 (Not Found)"
Otherwise, I'm able to delete any other note with no problem.
Here is my js code:
// display list of notes on the side
const noteContainer = document.querySelector(".column is-one-quarter")
const noteList = document.querySelector(".menu-list")
fetch('http://localhost:3000/api/v1/notes')
.then(function(response) {
return response.json();
})
.then(function(notes) {
notes.forEach(function(note) {
noteList.innerHTML += `<li id="list-item" data-id=${note.id}><a id="note" data-id=${note.id} class="menu-item">${note.title}</a><i id="delete" data-id=${note.id} class="fas fa-minus-circle has-text-grey-light hvr-grow"></i></li>`
})
})
// display details of each note
const noteDetail = document.querySelector(".note-detail")
noteList.addEventListener('click', function(event) {
if (event.target.className === "menu-item") {
fetch(`http://localhost:3000/api/v1/notes/${event.target.dataset.id}`)
.then(function(response) {
return response.json()
})
.then(function(note) {
noteDetail.innerHTML = `<h1 contenteditable="true" id="title" data-id=${note.id} class="subtitle is-2">${note.title}</h1><p contenteditable="true" id="body" data-id=${note.id} class="subtitle is-6">${note.body}</p><a id="save" data-id=${note.id} class="button is-small">Save</a>`
})
}
})
// i should be able to edit the title and body of a note when i click
// on it and it should save when i click on the button.
noteDetail.addEventListener('click', function(event) {
if (event.target.id === "save") {
const noteId = event.target.dataset.id
const editTitleInput = document.querySelector(`h1[data-id="${noteId}"]`)
const editBodyInput = document.querySelector(`p[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
method: "PATCH",
headers: {
'Content-Type': 'application/json',
'Accepts': 'application/json'
},
body: JSON.stringify({
title: editTitleInput.innerText,
body: editBodyInput.innerText
})
}).then(function(response) {
return response.json()
}).then(function(note) {
singleNote.innerText = editTitleInput.innerText
})
}
})
// when i click on the button, a form with a title and body input
// should display on the right.
const newNoteButton = document.querySelector("#create")
newNoteButton.addEventListener('click', function(event) {
fetch("http://localhost:3000/api/v1/notes")
.then(function(response) {
return response.json()
})
.then(function(note) {
noteDetail.innerHTML = `<input id="title" class="input subtitle is-5" type="text" placeholder="Title">
<textarea id="body" class="textarea subtitle is-5" placeholder="Body" rows="10"></textarea><a id="add" class="button has-text-black" style="margin-left: 594px;">Add Note</a>`
// when i click on 'add button', a new note with a title and body
// should be created and added to the list of notes.
const noteTitleInput = document.querySelector("#title")
const noteBodyInput = document.querySelector("#body")
const addNoteButton = document.querySelector("#add")
addNoteButton.addEventListener('click', function(event) {
// event.preventDefault()
fetch('http://localhost:3000/api/v1/notes', {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accepts': 'application/json'
},
body: JSON.stringify({
title: noteTitleInput.value,
body: noteBodyInput.value
})
}).then(function(response) {
return response.json()
}).then(function(note) {
noteList.innerHTML += `<li data-id=${note.id}><a id="note" data-id=${note.id} class="menu-item">${note.title}</a><i id="delete" class="fas fa-minus-circle has-text-grey-light hvr-grow"></i></li>`
})
})
})
})
// i should be able to delete a note when i click on the button.
noteList.addEventListener('click', function(event) {
// event.preventDefault()
if (event.target.id === "delete") {
const noteId = event.target.dataset.id
// const noteListItem = document.querySelector("#list-item")
const noteListItem = document.querySelector(`li[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
method: "DELETE",
})
// debugger
// lastNote = noteList.lastElementChild
// noteList.removeChild(lastNote)
// singleNote.parentElement.remove()
noteListItem.parentNode.removeChild(noteListItem)
noteDetail.innerHTML = ""
}
})
Here is my html code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css">
<link href="css/hover.css" rel="stylesheet" media="all">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<link rel="stylesheet" href="css/note.css">
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1 class="title is-1">Jot</h1>
<div class="columns">
<div class="column is-one-quarter">
<p class="menu-label" style="font-size:15px;">
Notes <i id="create" class="fas fa-plus-circle has-text-grey-light hvr-grow" style="margin-left: 10px; width: 20px; height: 30px; font-size: 24px;"></i>
</p>
<ul class="menu-list">
</ul>
</div>
<div class="column is-three-fifths">
<div class="note-detail">
</div>
</div>
<div class="column">
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Any help would be greatly appreciated. :)
You're nesting strings on these two lines:
const noteListItem = document.querySelector(`li[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
Your template literal is creating a string and you're putting that inside of quotes. For example, if your noteId is say 12. your code is ending up like this:
const noteListItem = document.querySelector("li[data-id="'12'"]")
const singleNote = document.querySelector("a[data-id="'12'"]")
I'm not 100% sure that's your issue but it's the first thing that popped out to me.
You can check out MDN to brush up on your Template literals (Template strings).