I have divs on my site, when I click one, a textbox appears unique to that div. When I press the Add Item button that’s supposed save the text, it gives me an error on the addListItem function:
Uncaught TypeError: Cannot read properties of undefined (reading ‘trim’)
Here are some of my functions regarding this case:
// Add a new list item
function addListItem(shapeId) {
const shape = $(`#${shapeId}`);
const shapeInfo = shape.data("info");
if (shapeInfo) {
const shapeInput = shape.find(".shape-input");
const newItem = shapeInput.val();
if (newItem.trim() !== "") {
if (!shapeInfo.items) {
shapeInfo.items = [];
}
shapeInfo.items.push(newItem);
shapeInput.val("");
populateShapeList(shape);
saveShapeData();
}
}
}
// Function to save shape data to local storage
function saveShapeData() {
const shapesData = [];
$(".shape").each(function() {
const shapeId = $(this).attr("id");
const shapeData = {
id: shapeId,
top: $(this).position().top,
left: $(this).position().left,
width: $(this).width(),
height: $(this).height(),
items: $(this).data("info") ? $(this).data("info").items : []
};
shapesData.push(shapeData);
});
localStorage.setItem("shapes", JSON.stringify(shapesData));
}
The code is not entirely mine, as far as I’m aware, the part with the trim function is trying to decide whether or not the input is empty, but the problem seems to appear there. Please correct me if I’m wrong, I’m no expert.
2
Answers
i think the issue was sometimes newItem getting undefined that why u are getting error.
just check one condition like if (newItem && newItem.trim() !== "") this time it will check first newItem is there then only it will exicute the next one.
try the updated code.i hope it will work..
The following example will generate a random shape and add it to the shapes in local storage.
When rendering, the shapes will be retrieved from local storage.