let user input grades, and display them in a table in svelte, at the start of the program fetch data from storage if available, and every time the user inputs something store it in json locally in javascript

To let the user input grades and display them in a table, we can create a Svelte component. The component will have an input field to allow the user to enter a grade, a button to add the grade to the table, and a table to display the grades. We will also store the grades in local storage using JSON.

Here is the code for the Svelte component:

<script>
  // Load grades from local storage if available
  let grades = JSON.parse(localStorage.getItem('grades')) || [];

  // Add a grade to the table
  function addGrade() {
    const input = document.getElementById('grade-input');
    const grade = input.value;
    // Add the grade to the array
    grades.push(grade);
    // Save the grades in local storage
    localStorage.setItem('grades', JSON.stringify(grades));
    // Clear the input field
    input.value = '';
  }
</script>

<div>
  <label for="grade-input">Enter a grade:</label>
  <input id="grade-input" type="text">
  <button on:click={addGrade}>Add Grade</button>
</div>

<table>
  <thead>
    <tr>
      <th>Grades</th>
    </tr>
  </thead>
  <tbody>
    {#each grades as grade}
      <tr>
        <td>{grade}</td>
      </tr>
    {/each}
  </tbody>
</table>
831 chars
38 lines

We first load the grades from local storage using JSON.parse(). If there are no grades, an empty array is created. The addGrade() function is called when the user clicks the "Add Grade" button. It gets the input value, adds it to the grades array, saves the array to local storage using JSON.stringify(), and clears the input field.

The table is created using a <table> element. The <thead> contains a single row with a header cell. The <tbody> contains the grades as rows with a single cell. We use a Svelte {#each} block to iterate over the grades array and create a row for each grade.

By using local storage and JSON, the grades will persist even after the user closes the browser.

gistlibby LogSnag