skip to Main Content

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


  1. // 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 && 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));
    }
    

    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..

    Login or Signup to reply.
  2. 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.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>jQuery + localStorage</title>
        <script
          src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
          integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
          crossorigin="anonymous"
          referrerpolicy="no-referrer"
        ></script>
        <style>
          .shape-list {
            position: relative;
          }
          .shape {
            position: absolute;
            border: thin solid red;
          }
        </style>
        <script>
          const defaultShape = {
            id: "box1",
            top: 10,
            left: 10,
            width: 100,
            height: 100,
            items: [],
          };
    
          $(function () {
            populateShapeList();
    
            $('form[name="add-shape"]')
              .find('[name="shape"]')
              .val(JSON.stringify(defaultShape, null, 2));
    
            $('form[name="add-shape"]').on("submit", (e) => {
              e.preventDefault();
              addListItem($(e.target).find('[name="shape"]'));
            });
          });
    
          // Add a new list item
          function addListItem($input) {
            const shape = $input.val();
            if (shape.trim().length > 0) {
              saveShape(JSON.parse(shape));
              populateShapeList();
              $input.val(JSON.stringify(randomShape(), null, 2));
            }
          }
    
          function populateShapeList($shape) {
            $(".shape-list").append(restoreShapes().map(fromObject));
          }
    
          function randomShape() {
            return {
              id: `box${restoreShapes().length + 1}`,
              top: randInt(0, 100),
              left: randInt(0, 100),
              width: randInt(10, 300),
              height: randInt(10, 300),
              items: [],
            };
          }
    
          function toObject($shape) {
            return {
              id: $shape.attr("id"),
              top: $shape.position().top,
              left: $shape.position().left,
              width: $shape.width(),
              height: $shape.height(),
              items: $shape.data("info") ? $shape.data("info").items : [],
            };
          }
    
          function fromObject(shape) {
            return $("<div>")
              .attr("id", shape.id)
              .addClass("shape")
              .css({
                top: `${shape.top}px`,
                left: `${shape.left}px`,
                width: `${shape.width}px`,
                height: `${shape.height}px`,
              })
              .data("info", { items: shape.items });
          }
    
          function saveShape(shape) {
            saveShapes(restoreShapes().concat(shape));
          }
    
          function saveShapes(shapes) {
            localStorage.setItem("shapes", JSON.stringify(shapes));
          }
    
          function restoreShapes() {
            return JSON.parse(localStorage.getItem("shapes") ?? "[]");
          }
    
          function randInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
          }
        </script>
      </head>
      <body>
        <h1>jQuery + localStorage</h1>
        <form name="add-shape">
          <textarea class="shape-input" name="shape" rows="10" cols="40"></textarea>
          <button id="add-btn" type="submit">Add</button>
        </form>
        <div class="shape-list"></div>
      </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search