newWorkout.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. export default {
  2. rendered: false,
  3. exerciseInputs: [],
  4. inputsDiv: document.getElementById("newWorkoutInputs"),
  5. render: function(){
  6. document.getElementById("newWorkoutName").focus();
  7. if(!this.rendered){
  8. this.buttons();
  9. this.addExerciseInput();
  10. this.rendered = true;
  11. }
  12. },
  13. buttons: function(){
  14. document.getElementById("newWorkoutBack").addEventListener("click", ()=>{
  15. changePage("home");
  16. });
  17. document.getElementById("newWorkoutFinish").addEventListener("click", this.createWorkout.bind(this));
  18. },
  19. addExerciseInput: function(){
  20. const label = document.createElement("label");
  21. this.inputsDiv.appendChild(label);
  22. const p = document.createElement("p");
  23. p.textContent = `Exercise # ${this.exerciseInputs.length+1}`;
  24. label.appendChild(p);
  25. const input = document.createElement("input");
  26. input.type = "text";
  27. input.placeholder = "Exercise Name";
  28. input.addEventListener("keyup", this.checkInputs.bind(this));
  29. label.appendChild(input);
  30. this.exerciseInputs.push(input);
  31. },
  32. checkInputs: function(){
  33. let emptyInputs = false;
  34. for(let i = 0; i < this.exerciseInputs.length; i++){
  35. if(this.exerciseInputs[i].value === "") emptyInputs = true;
  36. }
  37. if(!emptyInputs){
  38. this.addExerciseInput();
  39. }
  40. },
  41. createWorkout: function(){
  42. const name = document.getElementById("newWorkoutName").value;
  43. const exercises = []
  44. for(let i = 0; i < this.exerciseInputs.length; i++){
  45. if(this.exerciseInputs[i].value === "") continue;
  46. exercises.push({
  47. name: this.exerciseInputs[i].value,
  48. type: "weights"
  49. });
  50. }
  51. if(exercises.length === 0){
  52. notify("error", "Workout must contain at least one exercise");
  53. return;
  54. }
  55. fetch("/workout", {
  56. method: "POST",
  57. headers: {
  58. "Content-Type": "application/json"
  59. },
  60. body: JSON.stringify({
  61. name: document.getElementById("newWorkoutName").value,
  62. exercises: exercises
  63. })
  64. })
  65. .then(r=>r.json())
  66. .then((response)=>{
  67. if(response.error){
  68. notify("error", response.error.message);
  69. }else{
  70. notify("success", "New workout created");
  71. changePage("home", response);
  72. }
  73. })
  74. .catch((err)=>{
  75. notify("error", "ERROR: unable to create workout");
  76. })
  77. }
  78. }