0

I have a problem and it is the following: when I modify the dom with my file called 'guardarcambios.js' when reloading the web page the elements that I created are deleted, and I would like to know how I do so that this does not happen.

Here I share the code of my html and my javascript:

Code html 'index.php':

<!doctype html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <!-- InventoryBox-->
  <link rel="stylesheet" href="css/styles.css">

  <!-- Google Fonts: Roboto-->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">

  <!-- ICON-->
  <link rel="shortcut icon" href="resources/img/icon.png" type="image/x-icon">

  <title>Inventory Box</title>
</head>

<body>

  <nav class="navbar navbar-light bg-light border">
    <div class="row">
      <div class="col">
        <div class="container-fluid">
          <a class="navbar-brand " href="#">
            <img src="resources/img/icon.png" alt="" width="80" height="80" class="d-inline-block align-text-center">
            InventoryBox
          </a>
        </div>
      </div>
    </div>
    <div class="col">
      <div class="container-fluid">
        <form class="d-flex">
          <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>

  <!-- Menu CUD-->
  <div class="row border">
    <div class="col  mt-3 mb-3">
      <div class="col-12" style="width: fit-content; margin: auto;">
        <button data-bs-toggle="modal" href="#modalagregarproducto" role="button" style="width: 500px; height: auto;" class="btn ml-auto btn-primary" type="submit">Agregar nuevo
          producto</button>
      </div>
    </div>

    <!-- Vertically centered modal -->
    <div class="modal fade" id="modalagregarproducto" aria-hidden="true" aria-labelledby="modalagregarproducto" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="ModalToggleLabel">Agregar nuevo producto</h5>
            <button type="button" id="btn-close" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form class="" action="" method="post" enctype="multipart/form-data">
              <input type="file" class="form-control" id="file" name="file" size="20" required>
              <hr>
              <div id="preview">

              </div>
              <div class="row mb-3 mt-3">
                <div class="col-5">
                  <label class="mt-2" for="id">ID: </label>
                </div>
                <div class="col-7 ">
                  <input class="form-control" type="number" name="id" id="id" placeholder="ID" required>
                </div>
              </div>
              <div class="row mb-3">
                <div class="col-5">
                  <label class="mt-2" for="nombre">Nombre del producto: </label>
                </div>
                <div class="col-7">
                  <input class="form-control" type="text" name="nombreProducto" id="nombreProducto" placeholder="Nombre del producto" required>
                </div>
              </div>
              <div class="row mb-3">
                <div class="col-5">
                  <label class="mt-2" for="modeloProducto">Modelo: </label>
                </div>
                <div class="col-7">
                  <input class="form-control" type="text" name="modeloProducto" id="modeloProducto" placeholder="Modelo del producto" required>
                </div>
              </div>
              <div class="row mb-3">
                <div class="col-5">
                  <label class="mt-2" for="numeroProducto">Número: </label>
                </div>
                <div class="col-7 ">
                  <input class="form-control" type="number" name="numeroProducto" id="numeroProducto" placeholder="Número de productos" required>
                </div>
              </div>
              <div class="col d-grid gap-2">
                <input type="submit" id="guardarcambios" name="guardarcambios" class="btn btn-primary" data-bs-target="#ModalToggle2" value="Guardar cambios">
              </div>
            </form>
          </div>
          <div class="modal-footer">
          </div>
        </div>
      </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    <!-- JavaScript -->
    <script src="js/vistaprevia.js"></script>
    <script src="js/descartar.js"></script>
    <script src="js/guardarcambios.js"></script>
</body>

</html>

Code javascript 'guardarcambios.js':

window.onload = function () {
    const btnGuardarCambios = document.getElementById('guardarcambios')

    btnGuardarCambios.addEventListener("click", function () {

        // 1: Obtener los valores de los inputs por medio de los id.

        const imagen = document.getElementById("file").value // C:\fakepath\0-6277_firewatch-wallpaper-8k-hd-wallpaper-download-high-resolution.jpg
        console.log(imagen)

        const nombreProducto = document.getElementById("nombreProducto").value // Manilla
        const modeloProducto = document.getElementById("modeloProducto").value // 0x00 
        const numeroProducto = document.getElementById("numeroProducto").value // 25

        // 2: Crear cada uno de los elementos que conforman a una card en javascript.

        const createDiv = document.createElement("div") // <div></div>
        const createImg = document.createElement("img") // <img></img>
        const createDivBody = document.createElement("div") // <div></div>
        const createH5 = document.createElement("h5") // <h5></h5>
        const createP = document.createElement("p") // <p></p>
        const createButton1 = document.createElement("button") // <button></button>
        const createButton2 = document.createElement("button") // <button></button>

        // 3: Insertar los valores de los inputs en sus respectivos elementos creados.

        createImg.setAttribute("src", imagen) // <img src="C:\fakepath\0-6277_firewatch-wallpaper-8k-hd-wallpaper-download-high-resolution.jpg"></img>
        createImg.setAttribute("style", "width: 100px; heigt: 50px")
        createImg.setAttribute("class", "img-thumbnail")

        createH5.innerText = nombreProducto // <h5>Manilla</h5>
        createP.innerText = `Modelo producto: ${modeloProducto} Número de productos: ${numeroProducto}` // <p>Modelo producto: 0x00 Número de productos: 25</p>
        createButton1.innerText = "Modificar" // <button>Modificar</button>
        createButton2.innerText = "Eliminar" // <button>Eliminar</button>

        // 4: Estructurar el elemento

        createDiv.appendChild(createImg)
        createDiv.appendChild(createDivBody)
        createDivBody.appendChild(createH5)
        createDivBody.appendChild(createP)
        createDivBody.appendChild(createButton1)
        createDivBody.appendChild(createButton2)

        // 5: Mostrar en el window del navegador el elemento estructurado.

        document.body.appendChild(createDiv)
    })
}

I do not need to make the code, I just need to give me an idea of how I could make sure that what I modify with javascript is not deleted. I would appreciate it very much.

  • 1
    If you make changes in the DOM they exist only in the browser. If you don't make corresponding changes in the source code on the server they'll be lost when you refresh the page, unless you make the same changes again with JavaScript. – Tangentially Perpendicular Nov 13 '21 at 22:15

2 Answers2

0

You are not calling "guardarcambios.js" anywhere in your html file.

Also, not sure if it's due to copy and paste and probably isn't a biggie but no closing ">" on your </html :D

JamieCodes
  • 36
  • 5
0

I am not sure if this is the reason, but I don't have all of your JS files to confirm. When running on my local machine, it is showing the error in the below image.

[Error1

JamieCodes
  • 36
  • 5
  • you have discord, to share all the files, there are not many, or I can share it with a .ngrok link – Adalberto Granja Valencia Nov 13 '21 at 23:52
  • @AdalbertoGranjaValencia the issue is not missing files, this file I screenshot is one on my local pc. Check the top of your post here, you will see a link to another topic where this is discussed further and there you will find your answer and why you are having problems here :) – JamieCodes Nov 15 '21 at 21:36