Advertisement
GeorgiLukanov87

07. Students

Mar 1st, 2023
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.   const url = 'http://localhost:3030/jsonstore/collections/students';
  3.   loadStudentsInfo();
  4.  
  5.   const submitBtn = document.getElementById('submit');
  6.   const tableResults = document.querySelector('#results tbody');
  7.   const inputs = document.querySelector('#form .inputs');
  8.  
  9.   submitBtn.addEventListener('click', addNewStudent);
  10.  
  11.   function addNewStudent() {
  12.     let inputFristName = inputs.children[0].value;
  13.     let inputLastName = inputs.children[1].value;
  14.     let inputFacNumber = inputs.children[2].value;
  15.     let inputGrade = inputs.children[3].value;
  16.     if (inputFristName === '' || inputLastName === '' || inputFacNumber === '' || inputGrade === '') {
  17.       return;
  18.     }
  19.     fetch(url, {
  20.       method: 'POST',
  21.       headers: {
  22.         'content-type': 'application/json'
  23.       },
  24.       body: JSON.stringify({
  25.         'firstName': inputFristName,
  26.         'lastName': inputLastName,
  27.         'facultyNumber': inputFacNumber,
  28.         'grade': inputGrade
  29.       })
  30.     })
  31.       .then(res => res.json())
  32.  
  33.     document.location.reload();
  34.   }
  35.  
  36.  
  37.   function loadStudentsInfo() {
  38.     fetch(url)
  39.       .then(res => res.json())
  40.       .then(data => {
  41.         for (obj in data) {
  42.           let firstName = data[obj]['firstName']
  43.           let lastName = data[obj]['lastName']
  44.           let facultyNumber = data[obj]['facultyNumber']
  45.           let grade = data[obj]['grade']
  46.  
  47.           let newTr = document.createElement('tr');
  48.  
  49.           let firstNameTd = document.createElement('td');
  50.           firstNameTd.textContent = firstName;
  51.           let lastNameTd = document.createElement('td');
  52.           lastNameTd.textContent = lastName;
  53.           let facultyNumberTd = document.createElement('td');
  54.           facultyNumberTd.textContent = facultyNumber;
  55.           let gradeTd = document.createElement('td');
  56.           gradeTd.textContent = grade;
  57.  
  58.           newTr.appendChild(firstNameTd);
  59.           newTr.appendChild(lastNameTd);
  60.           newTr.appendChild(facultyNumberTd);
  61.           newTr.appendChild(gradeTd);
  62.  
  63.           tableResults.appendChild(newTr);
  64.         }
  65.       })
  66.   }
  67.  
  68. }
  69.  
  70. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement