본문 바로가기
개발공부/개발하다_발견함

Javascript로 새 Element를 생성했을때 form에 직접 붙이지 않고 form 내부의 요소에 붙이게 될 경우 form 전송이 되지 않는다.

by 맙소사 2022. 4. 6.

아 나 제목 길게 쓸 때 마다 무슨 라노벨 제목 같아서 웃기네

 

오늘의 발견은 제목 그대로의 내용이다.

목적 : 여러개의 첨부파일을 붙일 수 있는 게시판인데 input file을 줄줄이 나열해두니까 화면이 조금 못생긴 것 같아서 조금 수고를 들여서 보기도 예쁘고 뒷단에서 데이터 삽입할때 쓸데없는 회전을 줄일 수 있도록 일전의 createElement를 활용해 +버튼을 누를 때 마다 새 input file을 만들어서 첨부파일 div에 appendChild로 넣어줬다.

 

그런데 이상하게 기존에 처음 화면이 구성될때 존재하는 input file 태그 외에 appendChild로 첨부파일 div에 추가되는 친구들은 form으로 같이 전송이 안 되는거임. (왜지? 이유를 아시는 분은 제발 지식공유를 부탁드립니다.)

 

그래서 고민하다가 그냥 첨부파일div를 아예 form태그 바깥으로 빼낸 다음 글 내용을 전부 다 작성하고 폼 전송하기 전에 첨부파일 div를 form 태그에 appendChild 해줬다. 파일이 아주 잘 넘어가서 데이터베이스에 저장되는 것 까지 확인함.

 

아래 코드는 첨부파일을 추가하는 함수이고(변수명을 조금 바꿨는데 혹시나 오타가 있을수도 있음),

폼 전송 전에 폼에 해당 input들이 들어있는 div 하나만 appendChild 해주면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    //첨부파일 늘리기
    var atch_idx = 1;
    function atch_file_add(){
        if (atch_idx > 4){
            alert("첨부파일은 최대 5개 까지만 가능합니다.");
            return false;
        }
        var cooperation_file = document.createElement('input');
        var cooperation_file_hidden = document.createElement('input');
        
        cooperation_file.setAttribute("type""file");
        cooperation_file.setAttribute("id""cooperation_file_0"+atch_idx);
        cooperation_file.setAttribute("name""fileList["+atch_idx+"].uploadFileVO[0].fileData");
        
        cooperation_file_hidden.setAttribute("type""hidden");
        cooperation_file_hidden.setAttribute("value""cooperation_file_0"+atch_idx);
        cooperation_file_hidden.setAttribute("name""fileList["+atch_idx+"].fileType");
        
        //첨부파일 칸에 붙임
        var file_div = document.createElement('div');
        file_div.setAttribute("class""file_list");
        file_div.appendChild(cooperation_file);
        file_div.appendChild(cooperation_file_hidden);
        
        var upload = document.getElementById("upload");
        upload.appendChild(file_div);
        
        atch_idx += 1;
        if(atch_idx == 5){
            document.getElementById("atch_file_add_button").style.display = "none";
        }
    }
cs

 

끝.

댓글