Client Side/Jquery

[jquery]append 갯수 제한, remove 하나씩 삭제하기

Dev. Tool 2023. 12. 11. 00:57

<!-- Latest compiled and minified CSS -->

 

 

<!-- jQuery library -->

 

<!-- Latest compiled JavaScript -->

//jquery library 추가


<script type="text/javascript">

$(function() {

var maxAppend = 1; //버튼누른 횟수 저장

$('#add').click(function(){

if (maxAppend >= 5) return; // 5번째부터는 append 안되고 return 시키기

$('div').append('<input type="file">');

maxAppend++;

});


$('#remove').click(function() {

$('input:last-child').remove(); 

//.remove 하면 모든 input이 삭제되어 버리기 때문에 따로 input에 class나 id를 안줬으면 last-child로 마지막 것 부터 하나씩 잡아 지워나간다.

})

});


</script>


</head>

<body>

<!-- 최대 5개까지만 -->

<div>

<input type="file">


</div>

<h1>최대 5개까지 추가 가능</h1>

<button id="add">ADD</button>

<button id="remove">REMOVE</button>

</body>

 

 

문제점

 

그런데 이렇게 하니까 그냥 append만 했을 때는 문제가 없었는데 remove 후 다시 5개까지 채워주려 하니 이미 버튼 클릭 횟수가 5회를 채워서 더이상 추가가 안되는 문제점을 발견.

 

 

해결

$('#remove').click 이벤트 안에 maxAppend-- 를 추가해서 클릭 횟수를 감소시켜주면 반복이 가능하다.

 

출처 - https://mail.naver.com/v2/read/6/57651