개인프로젝트/기능프로그램_오늘뭐입지

20240524_옷 수정하기

일일일코_장민기 2024. 5. 24. 11:44
728x90

 

기존의 옷 출력 화면은 자바스크립트로 구현되었다.

 

그래서 옷 수정 버튼 및 수정 작업도 자바스크립트로 작동하는게 편하다...할 수 밖에 없다 인가?

 

아무

 

더보기
//옷 수정 상태로 변경
$(document).on("click", ".updateEvent", function () {
    var currentRow = $(this).closest("tr")                                 //버튼이 소속된 행을 찾음
    var categoryCell = currentRow.find(".category");            //categoryCell 찾기
    var clothdataCell = currentRow.find(".clothdata");          //clothdataCell 찾기
    var categoryText = categoryCell.text();                            //categoryText 찾기
    var clothdataText = clothdataCell.text();                          //clothdataText 찾기
    var updateCell = currentRow.find(".updateEvent")            //수정 버튼 찾기

    var selectHtml ='<select id="categoryForCloth" name="categoryForCloth">' +
                        '<option value="모자">모자</option>' +
                        '<option value="겉옷">겉옷</option>' +
                        '<option value="상의">상의</option>' +
                        '<option value="하의">하의</option>' +
                        '<option value="양말">양말</option>' +
                        '<option value="신발">신발</option>' +
                    '</select>';
    categoryCell.html(selectHtml);
    categoryCell.find('select').val(categoryText);

    clothdataCell.html("<input type='text' id='cloth' name='cloth' value='"+clothdataText+"'/>")

    updateCell.text("저장");
    updateCell.removeClass("updateEvent").addClass("saveEvent");
})

// 옷 업데이트 ajax
$(document).on("click", ".saveEvent", function () {
    var userid = $("#userid").val();
    var currentRow = $(this).closest("tr");                              // 버튼이 소속된 행을 찾음
    var categoryCell = currentRow.find(".category select");   // <select> 요소 찾기
    var clothdataCell = currentRow.find(".clothdata input");  // <input> 요소 찾기
    var updateCell = currentRow.find(".saveEvent");           // 저장 버튼 찾기

    var categoryText = categoryCell.val(); // 선택된 카테고리 값
    var clothdataText = clothdataCell.val(); // 입력된 옷 데이터 값

    $.ajax({
        type: "post",
        url: "/updateCloth",
        data: {
            id: updateCell.data("id"),
            userid: userid,
            category: categoryText,
            clothdata: clothdataText
        },
        success: function() {
            console.log("데이터 저장 성공");
        },
        error: function() {
            console.log("데이터 저장 실패");
        }
    });

    // 선택된 값과 입력된 값으로 셀을 업데이트
    categoryCell.closest(".category").text(categoryText);
    clothdataCell.closest(".clothdata").text(clothdataText);

    // 저장 버튼을 수정 버튼으로 변경
    updateCell.text("수정");
    updateCell.removeClass("saveEvent").addClass("updateEvent");
});
function viewMyClothes() {
    var userid = $("#userid").val()
    var allClothesField = $("#allClothesField")
    $.ajax({
        type: "post",
        url: "/selectAllClothes",
        data: {userid: userid},
        success: function (response) {
            var tableHtml = "<table>";
            tableHtml += "<tr><th>Category</th><th>Cloth</th><th>수정</th><th>삭제</th></tr>";
            response.forEach(function (cloth) {
                tableHtml += "<tr>";
                tableHtml += "<td class='category'>" + cloth.category + "</td>";
                tableHtml += "<td class='clothdata'>" + cloth.clothdata + "</td>";
                tableHtml += "<td class='updateEvent' data-id='" + cloth.id + "'>" + "수정" + "</td>>"
                tableHtml += "<td class='deleteEvent' data-id='" + cloth.id + "'>" + "x" + "</td>";
                tableHtml += "</tr>";
            });
            tableHtml += "</table>";

            // 생성된 표를 화면에 출력
            allClothesField.html(tableHtml);
        },
        error: function () {
            console.log("저장된 옷 불러오기 실패")
        }
    })
}

 

tableHtml += "<tr><th>Category</th><th>Cloth</th><th>수정</th><th>삭제</th></tr>";
response.forEach(function (cloth) {
    tableHtml += "<tr>";
    tableHtml += "<td class='category'>" + cloth.category + "</td>";
    tableHtml += "<td class='clothdata'>" + cloth.clothdata + "</td>";
    tableHtml += "<td class='updateEvent' data-id='" + cloth.id + "'>" + "수정" + "</td>>"
    tableHtml += "<td class='deleteEvent' data-id='" + cloth.id + "'>" + "x" + "</td>";
    tableHtml += "</tr>";
});
tableHtml += "</table>";

 

tableHtml 수정

- 헤더: 수정 파트 추가

- 바디: 각 컬럼 클래스 추가

 

var currentRow = $(this).closest("tr")                      //버튼이 소속된 행을 찾음
var categoryCell = currentRow.find(".category");            //categoryCell 찾기
var clothdataCell = currentRow.find(".clothdata");          //clothdataCell 찾기
var categoryText = categoryCell.text();                     //categoryText 찾기
var clothdataText = clothdataCell.text();                   //clothdataText 찾기
var updateCell = currentRow.find(".updateEvent")            //수정 버튼 찾기

 

- this와 closest를 사용하여 수정 버튼을 누른 행을 찾는다.

- 해당 행으로부터 각 컬럼의 셀과 데이터를 찾는다.

 

var selectHtml ='<select id="categoryForCloth" name="categoryForCloth">' +
                    '<option value="모자">모자</option>' +
                    '<option value="겉옷">겉옷</option>' +
                    '<option value="상의">상의</option>' +
                    '<option value="하의">하의</option>' +
                    '<option value="양말">양말</option>' +
                    '<option value="신발">신발</option>' +
                '</select>';
categoryCell.html(selectHtml);
categoryCell.find('select').val(categoryText);

clothdataCell.html("<input type='text' id='cloth' name='cloth' value='"+clothdataText+"'/>")

updateCell.text("저장");
updateCell.removeClass("updateEvent").addClass("saveEvent");

 

- html와 text메서드를 통해 각 컬럼의 셀에 데이터를 입력한다.

- 수정은 저장으로 바꾸고 class도 변경해준다.

 

var userid = $("#userid").val();
var currentRow = $(this).closest("tr");                   // 버튼이 소속된 행을 찾음
var categoryCell = currentRow.find(".category select");   // <select> 요소 찾기
var clothdataCell = currentRow.find(".clothdata input");  // <input> 요소 찾기
var updateCell = currentRow.find(".saveEvent");           // 저장 버튼 찾기

var categoryText = categoryCell.val(); // 선택된 카테고리 값
var clothdataText = clothdataCell.val(); // 입력된 옷 데이터 값

 

다시 저장 버튼을 누르면 작동되는 함수

- 마찬가지로 행의 정보를 찾는다.

- 여기에서 초기화하는 변수들은 DTO로 만들어 백엔드로 넘어갈 것이다.

 

//옷 추가 및 수정하기 메서드
@PostMapping("/updateCloth")
public void updateCloth(ClothDTO updatedCloth){
    clothService.updateClothes(updatedCloth);
}

- 백엔드의 url은 옷 추가 메서드와 동일하다

- save를 사용하는 jpa이기 때문에 가능하다.

 

// 선택된 값과 입력된 값으로 셀을 업데이트
categoryCell.closest(".category").text(categoryText);
clothdataCell.closest(".clothdata").text(clothdataText);

// 저장 버튼을 수정 버튼으로 변경
updateCell.text("수정");
updateCell.removeClass("saveEvent").addClass("updateEvent");

- ajax가 종료되면 현재 input과 select로 바뀌어 있는 셀을 text로 바꾼다.

- 저장 버튼도 원래대로 수정 버튼으로 변경하고, 클래스도 바꾸어준다.