so the following function appends the given text to the existing text in the editor, but what I want is to totally replace whatever exists.
const sendTextToEditor = (editorState, text) => {
setEditorState(insertText(editorState, text))}
const insertText = (editorState, text) => {
const currentContent = editorState.getCurrentContent();
const currentSelection = editorState.getSelection();
const newContent = Modifier.replaceText(
currentContent,
currentSelection,
text
);
const newEditorState = EditorState.push(
editorState,
newContent,
'insert-fragment'
);
return EditorState.forceSelection(
newEditorState,
newContent.getSelectionAfter()
)};
I have tried to search how to clear the text editor before populating it with the desired text, using clearEditorContent from draftjs-utils
setEditorState(clearEditorContent(editorState));
but it says clearEditorContent is undefined
So I found out that if I can't clear the editor, I can select everything inside and simply replace it
here is how I did it.
const sendTextToEditor = (editorState, text) => {
setEditorState(insertText(editorState, text));
};
const insertText = (editorState, text) => {
const currentContent = editorState.getCurrentContent();
//selecting everything in the editor to be replaced
const firstBlock = currentContent.getFirstBlock()
const lastBlock = currentContent.getLastBlock()
const currentSelection = new SelectionState({
anchorKey: firstBlock.getKey(),
anchorOffset: 0,
focusKey: lastBlock.getKey(),
focusOffset: lastBlock.getLength(),
hasFocus: true
})
const newContent = Modifier.replaceText(
currentContent,
currentSelection,
text
);
const newEditorState = EditorState.push(
editorState,
newContent,
'insert-characters'
);
return EditorState.forceSelection(
newEditorState,
newContent.getSelectionAfter()
);
};
Related
I am having a hard time trying to figure out how to get the the value from every new Li and reduce it (add) to then output to my h2. Can't figure out what I am doing wrong. Any help would be greatly appreciated! Codepen: https://codepen.io/Chasehud26/pen/Poagjwy
I tried to console.log different variables to see if there were any hints of what is going wrong.
const form = document.querySelector("form")
const nameInput = document.querySelector("#name-input")
const priceInput = document.querySelector("#price-input")
const button = document.querySelector("button")
const nameUl = document.querySelector("#item-name")
const priceUl = document.querySelector("#item-price")
const h2 = document.querySelector("h2")
const nameLi = document.createElement("li")
const priceLi = document.createElement("li")
form.addEventListener("submit", function (e) {
e.preventDefault()
let nameVal = nameInput.value
let priceVal = priceInput.value
const nameLi = document.createElement("li")
const priceLi = document.createElement("li")
nameUl.appendChild(nameLi)
nameLi.innerHTML = nameInput.value
priceUl.appendChild(priceLi)
priceLi.textContent = `${priceInput.value}`
showTotals()
})
//TRYING TO ADD TOGETHER ALL THE PRICE VALUES AND THEN PUT IT TO MY H2//
function showTotals() {
const priceList = document.querySelectorAll("li")
for (let priceLists of priceList) {
const total = []
total.push(parseFloat(priceLists.textContent));
const totalMoney = total.reduce(function (total, item) {
total += item;
return total;
}, 0);
const finalMoney = totalMoney.toFixed(2);
h2.textContent = finalMoney;
}
}
You need to have your const total [] array initialized outside of the for loop. also, when you setup your <li> decorators, you need to differentiate between the number and non-number fields, since the way you had it, it was trying to add the text 'li' fields also:
/// truncated for clarity
const nameLi = document.createElement("li")
const priceLi = document.createElement("li")
priceLi.classList.add('num') // <== this line added
//// =================
function showTotals() {
const priceList = document.querySelectorAll("li.num") // added class
const total = [] // <== move this to here
for (let priceLists of priceList) {
total.push(parseFloat(priceLists.textContent));
const totalMoney = total.reduce(function (total, item) {
total += item;
return total;
}, 0);
const finalMoney = totalMoney.toFixed(2);
h2.textContent = finalMoney;
}
i'm trying to create a simple To-do list, and my question is how do i get all elements of a single item in localStorage displayed?
pushing things into localStorage in a form of an array works fine, but only thing I see on my page is the first index of the "tasks" array.
const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")
let localStorageContent = localStorage.getItem("tasks")
let tasks = []
function createTask(){
if(inputEl.value.length != 0){
const newDiv = document.createElement("div")
newDiv.classList.add("task")
const newParagraph = document.createElement("p")
const newCancelBtn = document.createElement("button")
newCancelBtn.classList.add("cancelBtn")
newCancelBtn.textContent = "X"
const newDoneBtn = document.createElement("button")
newDoneBtn.classList.add("doneBtn")
newDoneBtn.textContent = "Done"
todoListContainer.appendChild(newDiv)
newDiv.appendChild(newParagraph)
newDiv.appendChild(newCancelBtn)
newDiv.appendChild(newDoneBtn)
//^^ Creating a container for a new task, with all its elements and assigning the classes^^
tasks.push(inputEl.value)
localStorage.setItem("tasks", JSON.stringify(tasks))
inputEl.value = ""
newParagraph.textContent = JSON.parse(localStorageContent)
errorMsg.textContent = ""
}else{
errorMsg.textContent = "You have to type something in!"
errorMsg.classList.toggle("visibility")
}
}
submitBtn.addEventListener("click", () =>{
createTask()
})
When you execute JSON.parse(localStorageContent) you convert your string into an array, that's right.
But:
newParagraph.textContent = JSON.parse(localStorageContent)
is the same as:
newParagraph.textContent = JSON.parse(localStorageContent)[0]
So, you have to loop through your JSON.parse(localStorageContent)
array... Therefore, create a new variable:
let tasksItem = JSON.parse(localStorageContent)
and loop on with .forEach method
I'm very new to javascript/dev so I hope there is a an obvious solution that I've not thought of. My code returns search items from TVMaze.com API. The feature giving me trouble is the incremental search (as a user types in input box, the code returns and displays images by creating a new div and appending images, removing and replacing the an div).
My problem is that on deleting all characters from input box, I receive the error: "Uncaught (in promise) TypeError: shows is not iterable" which I suppose means that there is no object to iterate over? Thanks in advance for any help.
const input = document.querySelector("#query");
input.addEventListener("input", async function (e) {
e.preventDefault();
const searchTerm = e.target.value;
const config = { params: { q: searchTerm } };
const res = await axios.get(`http://api.tvmaze.com/search/shows?`, config);
makeImages(res.data);
clearList();
});
const makeImages = (shows) => {
const div = document.createElement("div");
for (let result of shows) {
if (result.show.image) {
const img = document.createElement("IMG");
img.className += "resultImage";
img.src = result.show.image.medium;
const title = document.createElement("h3");
title.className += "resultTitle";
title.innerText = result.show.name;
const year = document.createElement("h4");
year.className += "score";
year.innerText = result.show.premiered;
var sub = year.innerText.substring(0, 4);
var yearNum = parseInt(sub);
div.append(year);
div.append(img);
div.append(title);
document.body.appendChild(div);
}
if (yearNum <= 2000) {
var retro = document.createElement("h5");
retro.className = "retro";
retro.innerText = "retro";
div.append(retro);
}
}
};
let clearList = () => {
var allImg = document.querySelectorAll("IMG");
if (allImg.length === 0) {
document.createElement("div");
return makeImages();
}
var oldDiv = document.querySelector("div");
oldDiv.remove();
console.log(oldDiv);
};
I'm trying to delete the form input posted onto the DOM, but the removeChild code isn't functioning, When inspecting the console I will be given an error which is: materialize.min.js:6 Uncaught TypeError: Cannot read property 'M_Modal' of null at HTMLBodyElement.value (materialize.min.js:6)
// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
});
//Delete Exercises
const delExerciseBtn = document.querySelector('.del-exercise-btn');
delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
const h6 = e.target.parentElement;
h6.removeChild(e.target);
}
});
// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get Input Value
const value = exerciseForm.querySelector('input[type="text"]').value;
// Create Elements
const h6 = document.createElement('h6');
// Add Content
h6.textContent = value;
// Append To Dom
addExerciseDom.appendChild(h6);
});
For Multiple Values of h6
Best to add id with each new h6
Check on weight and exercise
// Materialize Initialization Of Autocomplete, Exercise.
document.addEventListener('DOMContentLoaded', () => {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems,{
data: {
"Lat Pull Down": null,
"Lat Down": null,
},
limit:2,
minLength:1,
});
});
// Materialize Initialization Of Box Select, Sets and Reps.
document.addEventListener('DOMContentLoaded', () => {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
// Materialize Initialization Of Weights CharacterCount
document.addEventListener('DOMContentLoaded', () => {
var textNeedCount = document.querySelectorAll('.weightcountercount');
M.CharacterCounter.init(textNeedCount);
});
//need to put restrition on the number typed into the box without it submitting
// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
});
// ------------ Add Form's Inputs Onto The HomePage----------------
//-------------Exercises------------
// Delete Exercises From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');
delExerciseBtn.addEventListener('click', (e) => {
// Remove Form Input
const h6_e = document.getElementById('h6_exercise');
h6_e.remove();
// Remove Disable Btn
disabledExersiceBtn.removeAttribute('disabled');
});
// Add User's Exercises To The Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');
exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get Input Value
const value = exerciseForm.querySelector('input[type="text"]').value;
// Create Elements
// const h6 = document.createElement('h6');
//for exercise
const h6_exercise = document.createElement('h6');
// Add Content
h6_exercise.textContent = value;
//adding id
h6_exercise.setAttribute("id", "h6_exercise");
// Append To Dom
addExerciseDom.appendChild(h6_exercise);
//Disable Btn
disabledExersiceBtn.setAttribute('disabled', 'disabled');
});
//---------------------Weight----------------------
// Delete Exercises From The Dom
const delWeightBtn = document.querySelector('.del-weight-btn');
delWeightBtn.addEventListener('click', (e) => {
// Remove Form Input
let h6_r = document.getElementById('h6_weight');
h6_r.remove();
});
// Add User's Weight To The Dom.
const addWeightDom = document.querySelector('.weight-dom');
const weightForm = document.querySelector('.weight-form');
weightForm.addEventListener('submit', (e) => {
e.preventDefault();
if(document.getElementById('h6_weight'))
{
let h6_r = document.getElementById('h6_weight');
h6_r.remove();
}
// Get Input Value
const value = weightForm.querySelector('input[type="number"]').value;
const value1 = weightForm.querySelector('input[type="text"]').value;
//console.log(value, value1);
// Create Elements
const h6_weight = document.createElement('h6');
h6_weight.setAttribute('id','h6_weight')
//h6.classList.add("center");// not working
// Add Content
h6_weight.textContent = value + " " + value1;
// Append To Dom
addWeightDom.appendChild(h6_weight);
});
// ------------------Add Exercises Colum----------------------
//const addMoreBtn = document.getElementById("addmorebtn");
////const addColums = document.getElementById("addcolumns");
//addMoreBtn.addEventListener('click', (e) => {
// e.preventDefault();
// const text =
// `<div class="col s4 height"></div>
// <div class="col s2 height "></div>
// <div class="col s2 height"></div>
// <div class="col s2 height"></div>
// <div class="col s2 height"></div>`
//const position = "beforeend";
//addColums.insertAdjacentHTML(position, text);
//});
You can do it like this
// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
});
//Delete Exercises
const delExerciseBtn = document.querySelector('.del-exercise-btn');
delExerciseBtn.addEventListener('click', (e) => {
const h6 = document.getElementsByTagName('h6')[0];
h6.remove();
});
// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');
exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get Input Value
const value = exerciseForm.querySelector('input[type="text"]').value;
// Create Elements
const h6 = document.createElement('h6');
// Add Content
h6.textContent = value;
// Append To Dom
addExerciseDom.appendChild(h6);
//Disable Btn
disabledExersiceBtn.setAttribute('disabled', 'disabled');
});
The logic seems sound but my ul is not displaying what I am asking it to. I have used console.logs and I am for sure getting poem in the function displayPoem(poem) but it isn't showing up when I button click. Any help would be greatly appreciated!
const inputsList = document.querySelector('ol');
const poemsList = document.getElementById('savedThoughts');
const form = document.getElementById('')
const submitButton = document.getElementById('submitThoughts');
const startButton = document.querySelector('#startButton')
startButton.onclick = () => {
const ranNum = generateRanNum();
generateInputs(ranNum)
changeToRestartText()
}
submitButton.onclick = () => {
const poem = savePoem();
console.log(poem)
displayPoem(poem);
clearForm()
}
const generateRanNum = () => {
let randomNumber = Math.floor(Math.random() * 20);
return randomNumber
}
const changeToRestartText = () => {
startButton.textContent = 'Restart Game'
}
const generateInputs = (ranNum) => {
const listItem = document.createElement('li');
for(let i = 1; i <= ranNum; i++){
const input = document.createElement('input');
listItem.appendChild(input).setAttribute('type', 'text');
console.log(ranNum)
}
inputsList.appendChild(listItem);
}
const savePoem = () => {
let poemArr = [];
const input = document.querySelectorAll('input');
input.forEach(element => {
poemArr.push(element.value);
})
// console.log(poemArr)
return poemArr;
}
const displayPoem = (poem) => {
const savedPoem = document.createElement('li')
const savedText = document.createElement('span')
const deletePoem = document.createElement('button')
console.log(poem)
savedPoem.appendChild(savedText);
savedText.textContent = poem.toString();
savedPoem.appendChild(deletePoem);
deletePoem.textContent = 'Delete';
poemsList.appendChild(savedPoem)
deletePoem.onclick = e => {
poemsList.removeChild(savedPoem);
}
}
const clearForm = () => {
const inputLi = document.querySelectorAll('li');
inputLi.forEach(element => {
element.remove()
})
}
small html segment
<div >
<ul id="savedThoughts">
</ul>
</div>
Your saved list items aren't showing up because your submit onclick calls displayPoem which creates list items and then calls clearForm which removes all list items on the page. Try inputLi = document.querySelectorAll('ol > li').