본문 바로가기
JAVASCRIPT & JQUERY

[HTML&JQUERY&Java] 태그 추가 삭제 및 다중insert 기능!! (영상 有)

by GoodDayDeveloper 2021. 10. 20.
반응형

안녕하세요.

오늘은 태그를 추가하고 삭제하는 방법과 추가한 태그 값을 insert하는 방법을 정리해보았습니다.

 

구현 화면입니다.

여기서 중요한 것은 태그를 추가하거나 삭제할 때, 순번이 알맞게 유지되어야 한다는 점과,

태그 수가 어떻게 됬건 그 값을 서버에서 처리할 수 있도록 다중 처리하는 방법이 중요하겠네요!

 

 

 

 


create.jsp (Html)

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<div id="contAreaBox">
<form name="inputForm" id="inputForm" method="post" onsubmit="return _onSubmit(); return false;" action="${path}/adms/cmanage/contractManage/create_action.do">  
<div class="search-card card">
<div class="card-body">
<div class="form-inline">
    <label class="control-label me-2" for="">프로젝트명</label><br/>
    <input type="text" id="fs_title" name="fs_title" value="" placeholder="" class="form-control me-2 hasDatepicker" style="width:100%; margin-left:10px; margin-top:10px; ">
</div>
</div>
</div>
 
<h4 class="mt-5"><i class="bi bi-arrow-right-circle"></i> STEP 1. Data import</h4>
<div class="row">
<div class="col-lg-8 form-inline"><h5 class="mt-4 ms-sm-1"><i class="bi bi-check-circle-fill"></i> DATA import</h5></div>
</div>
 
<div class="table-responsive mt-2">
<table id="resTb" class="table table-striped table-bordered text-center tbl_List" name="tableStandard">
<colgroup>
    <col width="5%">
    <col>
    <col width="20%">
    <col width="20%">
    <col width="8%">
</colgroup>
<thead>
    <tr>
        <th>NO</th>
        <th>DATA import</th>
        <th>Group</th>
        <th>Sample</th>
        <th>DATA 추가</th>
    </tr>
</thead> 
<tbody>
<input type="hidden" id="tdCount" name="tdCount" />
<c:set var="k" value="0" />
    <tr id="Td" class="tdCount">
        <td id="tdNo_${k}" class="tdNo">1</td>
        <td>
            <select name="fss_fileType" id="fss_fileType_${k}" class="form-control" style="width:30%">
                <option value="fastq">fastq</option>
                    <option value="GZ">GZ</option>
            </select>
            <input type="file" name="fss_file" id="fss_file_${k}" accept="image/*" style="width:30%">
        </td>
        <td><input type="text" name="fss_group" id="fss_group_${k}" value="" style="width:300px" class="form-control fss_group"></td>
        <td><input type="text" name="fss_sample" id="fss_sample_${k}" value="" style="width:300px" class="form-control"></td>
        <td>
        <a href="javascript:void(0);" class="btn  btn  btn-danger btn-sm pmBtn" onclick="addTag(); return false;">+</a>
        <a href="javascript:void(0);" class="btn  btn  btn-danger btn-sm pmBtn" onclick="delTag(this); return false;">-</a>
        </td>
    </tr>
</tbody>
</table>
</div>
</form>
</div>
 
cs

 

Html에서는 보통의 등록페이지 처럼 꾸민 다음, 세가지 특징이 있습니다.

 

1. 추가할 tr태그에 'tdCount'란 class를 추가해줍니다. 

- tdCount를 가지고 제이쿼리에서 for문을 돌리면서 태그를 추가하고 제거하는데 사용할겁니다.

 

2. k변수를 설정하여 각 입력칸의 아이디 값에 _${k}를 넣어 구분을 짓습니다.

- 유효성 검사 및 컨트롤러로 가져가기 위한 작업을 합니다.

 

3. 태그를 추가/제거 하기 위해서 + 와 -에 onclick으로 함수를 설정합니다.

- 함수를 호출하여 제이쿼리에서 태그를 추가하고 제거할 예정입니다.

 

 

 

create.jsp (Jquery)

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<script type="text/javascript">
 
 
function _onSubmit(){
 
var tdCount = $(".tdCount").size();
$("#tdCount").val(tdCount);
 
if( $("#fs_title").val() == ""){
  alert("프로젝트명을 작성해주세요.");  
  $("#fs_title").focus();
  return false;
}
 
for(var i=0; i < tdCount; i++){
  
  if( $("#fss_fileType_"+i).val() == "" ){
    alert("타입을 선택해주세요.");  
    $("#fss_fileType_"+i).focus();
    return false;
  }
  
  if( $("#fss_file_"+i).val() == "" ){
    alert("파일을 선택해주세요.");  
    $("#fss_file_"+i).focus();
    return false;
  }
  
  if( $("#fss_group_"+i).val() == "" ){
    alert("그룹을 작성해주세요.");  
    $("#fss_group_"+i).focus();
    return false;
  }
  
  if( $("#fss_sample_"+i).val() == "" ){
    alert("샘플을 작성해주세요.");  
    $("#fss_sample_"+i).focus();
    return false;
  }
  
}
 
if(!confirm(gTxt("confirm.save"))){
  return false;
}
}
 
function addTag(){
var idx = $(".tdCount").size();
var no = idx+1;
var addText ='<tr id="Td_'+ idx +'" class="tdCount">'
              +'<td id="tdNo_'+idx+'" class="tdNo">' + no + '</td>'
              +'<td>'
              +'<select name="fss_fileType" id="fss_fileType_'+idx+'" class="form-control" style="width:30%">'
              +'<option value="fastq">fastq</option>'
              +'<option value="GZ">GZ</option>'
              +'</select>'
              +'<input type="file" name="fss_file" id="fss_file_'+idx+'" accept="image/*" style="width:30%">'
              +'</td>'
              +'<td><input type="text" name="fss_group" id="fss_group_'+idx+'" style="width:300px" class="form-control fss_group"></td>'
              +'<td><input type="text" name="fss_sample" id="fss_sample_'+idx+'" style="width:300px" class="form-control"></td>'
              +'<td>'
              +'<a href="javascript:void(0);" class="btn  btn  btn-danger btn-sm pmBtn" onclick="addTag(); return false;">+</a>'
              +'<a href="javascript:void(0);" class="btn  btn  btn-danger btn-sm pmBtn" onclick="delTag(this); return false;">-</a>'
              +'</td>'
              +'</tr>';
              
              
var tbHtml = $(".tdCount:last");
tbHtml.after(addText); 
}
 
function delTag(ths){
var idx = $(".tdCount").size();
if(idx > 1){
  var $tr = $(ths).parents("tr");
  $tr.remove();
  
  $(".tdNo").each(function(index){
    var tagId = $(this).attr('id''tdNo_'+index);
    $(tagId).text(index+1);
  });
}else{
  alert("최소 한개의 행은 존재하여야합니다.")
}
}
 
 
</script>
cs

 

유효성 검사 (function _onSubmit)

Html의 form태그에 _onsubmit 함수를 생성하여 유효성 검사를 합니다.

tr태그에 걸어놨던 클래스인 tdCount의 size를 tdCount 변수에 넣습니다.

이 사이즈는 컨트롤러에서 활용하기 때문에 val에 넣어주고요.

사이즈 값을 가지고 for문을 통해서 아이디값을 돌면서 유효성 검사를 해줍니다.

 

 

태그 추가 (function addTag())

유효성 검사와 마찬가지로 tdCount의 사이즈값을 idx 변수에 넣어줍니다.

태그 추가를 눌렀을땐 기존 사이즈 순번보단 하나가 추가되니 no라는 변수에 +1 값을 다시 넣어주죠

그리고 addText에 td값들을 html태그와 마찬가지로 넣어줍니다.

기존 html태그에서 ${k}와 같이 구분짓기 위해 idx를 넣어줍니다. idx는 기존 태그보단 하나 더 큰 숫자겠죠.

그리고 tbHtml변수에 tr태그에 위치한 tdCount 클래스의 뒷편에 :last 를 설정해놓고

tbHtml의 다음 (after)에 addText를 넣어주면 됩니다.

 

 

태그 추가 (function delTag())

이 역시 tdCount를 통해서 td사이즈를 불러옵니다.

그리고 1보다 클 경우에는 버튼 누른 자신의 값의 어미태그인 tr를 remove 를 통해 삭제해줍니다.

삭제를 한 다음 순번에 추가한 tdNo 클래스를 반복하여

tagId 변수에 attr를 통해서 id값을 재 설정한 다음, text를 통해 재 설정 값을 넣어주면 됩니다. 

1보다 작을 경우에는  else를 통해  알람창이 뜨도록 하는거죠.

 

 

이로써 jsp부분은 마무리가 되었습니다.

 

 

반응형

 

Controller (create_action)

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@RequestMapping(value = "/adms/cmanage/contractManage/create_action.do", method = RequestMethod.POST)
public String create_action(
    @ModelAttribute("searchVO") storeVO searchVO,
    @RequestParam(required = false, value = "tdCount") Integer tdCount,
    RedirectAttributes redirectAttributes,
    HttpServletRequest request,
    ModelMap model) throws Exception {
 
LoginVO loginVO = loginService.getLoginInfo();
 
Map<String, Object> resMap = new HashMap<String, Object>();
 
try{
    
    int fs_idx = storeService.createMainWork(searchVO);
    
 
    List<storeOrganismVO> storeList = new ArrayList<storeOrganismVO>();
    
    if (tdCount > 0) {
        String[] fss_fileType            =  request.getParameterValues("fss_fileType"== null ? new String[tdCount] : request.getParameterValues("fss_fileType");           
        String[] fss_file            =  request.getParameterValues("fss_file"== null ? new String[tdCount] : request.getParameterValues("fss_file");                       
        String[] fss_group           =  request.getParameterValues("fss_group"== null ? new String[tdCount] : request.getParameterValues("fss_group");                     
        String[] fss_sample         =  request.getParameterValues("fss_sample"== null ? new String[tdCount] : request.getParameterValues("fss_sample");                 
        
        for (int i = 0; i < tdCount.intValue(); i++) {
            storeOrganismVO stVO = new storeOrganismVO();
            stVO.setSite_code(loginService.getSiteCode());
 
            stVO.setFs_idx(fs_idx);
            stVO.setFss_fileType(fss_fileType[i]);
            stVO.setFss_file(fss_file[i]);
            stVO.setFss_group(fss_group[i]);
            stVO.setFss_sample(fss_sample[i]);
            storeList.add(stVO);
            stVO = null;
        }
    }
    
    storeService.insertFssVO(storeList);
    
    resMap.put("res""ok");
    resMap.put("msg""저장하였습니다.");
 
}catch(Exception e){
    System.out.println(e.toString());
    resMap.put("res""error");
    resMap.put("msg""txt.fail");
}
 
redirectAttributes.addFlashAttribute("resMap", resMap);
return "redirect:/specimen/store/list.do";
}
cs

 

여기서는 메인테이블과 서브테이블 두개를 insert합니다.

RequestParam으로 td사이즈 값을 넣어준 tdCount 활용하기 위해서 가져옵니다.

 

우선 메인테이블을 insert하고 idx값을 변수에 저장해줍니다.

그리고 서브테이블 insert할 데이터를 담을 배열변수를 만들어줍니다. (storeList)

만약에 td사이즈가 0보다 크면 request.getParameterValues를 통해서 다중 아이디 값을 가져옵니다.

그리고  tdCount의 사이즈만큼 반복문을 통해서 storeList에 담아주고

서브테이블을 저장합니다. (storeService.insertFssVO(storeList);)

 

 

서비스 구현 부분에 로직이 하나 더 있습니다.

 

 

ServiceImpl (create_action)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void insertFssVO(List<storeOrganismVO> storeList) throws Exception {
    try{
        for(storeOrganismVO stVO : storeList){
            int fss_idx = createSubWrokF(stVO);
            if(fss_idx == 0){
                throw new RuntimeException();
            }
        }
    }catch(Exception e){
        throw new RuntimeException();
    }
}
cs

 

리스트 만큼 for문을 돌면서 insert를 시키는거죠. 

insert는 보통의 isnert문과 같습니다.

 

 

 

 

 

아래는 연계되는 기능의 포스팅입니다.

[Jquery] 입력 그룹 값 합계 계산 방법!! (영상 有)

반응형

댓글