본문 바로가기

WEB/내맘대로 코딩

선택요소 추가 및 삭제

요소들을 추가, 삭제함에 있어 상당히 중요하게 다뤄지는 배열 메소드

indexOf, splice, push, pop만 사용했으나, 그외 메소드들도 정리 필요!

참고url: 1,2,3

 

See the Pen MWaeLZY by rainydaymusickr (@rainydaymusickr) on CodePen.

 

 

 

<h1>가장 좋아하는 메뉴는?</h1>
<div class="checkboxes">
	<div class="checkbox">
		<input type="checkbox" name="chk" id="jok">
		<label for="jok">방어회</label>
	</div>
	<div class="checkbox">
		<input type="checkbox" name="chk" id="osam">
		<label for="osam">산낙지탕탕이</label>
	</div>
	<div class="checkbox">
		<input type="checkbox" name="chk" id="jjuku">
		<label for="jjuku">오삼불고기</label>
	</div>
	<div class="checkbox">
		<input type="checkbox" name="chk" id="san">
		<label for="san">족발</label>
	</div>
	<div class="checkbox">
		<input type="checkbox" name="chk" id="bang">
		<label for="bang">쭈꾸미볶음</label>
	</div>
</div>
<button type="button" class="add">추가</button>
<div class="boxes">
<!-- 추가되는 코드형태	
	<div class="box">
		<span class="name">족발 <button type="button" class="del">족발 삭제</button></span>		
	</div> -->
</div>
:root{font-size:62.5%;}
body{font-size:2.3rem;}
h1{margin:2rem;}
.checkboxes,
.boxes {width:100%;margin:20px 0;white-space:nowrap;font-size:0;}
.checkboxes .checkbox,
.boxes .box {position:relative;display:inline-block;padding:10px;font-size:1.5rem;}
.checkboxes .checkbox input {position:absolute;visibility:hidden;width:1px;height:1px;margin-top:-1px;color:transparent;}
.checkboxes .checkbox input + label {
	display:block;
	padding:5px;
	outline: 0;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	-webkit-box-shadow: inset 0 0 0 2px #0064de;
	-moz-box-shadow: inset 0 0 0 2px #0064de;
	box-shadow: inset 0 0 0 2px #0064de;
	color: #0064de;
}
.checkboxes .checkbox input:checked + label {
	-webkit-box-shadow: inset 0 0 0 2px crimson;
	-moz-box-shadow: inset 0 0 0 2px crimson;
	box-shadow: inset 0 0 0 2px crimson;
	color: crimson;
}
.thumb{width:100px;}
.thumb img{max-width:100%;}
.add {display:block;width:100%;height:50px;margin:0 auto;padding:1.5px 2px;border:1px solid #00256c;
	-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;max-width:200px;
background-color:#00256c;color:#fff;font-weight:700;font-size:1.6rem;line-height:1.57;text-decoration:none;text-align:center;cursor:pointer;}
.boxes .name {
	padding:5px;
	outline: 0;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	-webkit-box-shadow: inset 0 0 0 2px #666;
	-moz-box-shadow: inset 0 0 0 2px #666;
	box-shadow: inset 0 0 0 2px #666;
	color: #666;	
}
.boxes .del {overflow:hidden;display:inline-block;width:20px;height:20px;margin-top:-2px;background:url('https://static12.samsungcard.com/images/directinsurance/common/new/btn_lypop_close.png') no-repeat center;border:0;color:transparent;text-indent:-999px;vertical-align:middle;}
arr1 = [];
arr2 = [];
html = '';
//체크되면 배열추가, 해제되면 배열삭제
$('.checkboxes .checkbox').each(function(){
	$(this).find('input').change(function(){
		if( $(this).prop('checked') == true ){
			//console.log( $(this).next('label').text() );
			arr1.push( $(this).next('label').text() );
			arr1.sort();
			//console.log(arr1);
		}else{
			//console.log( $(this).next('label').text() );
			var popIdx = arr1.indexOf( $(this).next('label').text()  );
			if( popIdx > -1 ){
				arr1.splice( popIdx, 1 );
			}
			arr1.sort();
			//console.log(arr1);
		}
		
	});

});

$('.add').bind('click',function(){
	$('.boxes').html('');
	arr2 = [];
	html = '';

	//배열 병합후 중복제거
	var unique = arr1.concat(arr2);
    for(var i=0; i<unique.length; ++i) {
        for(var j=i+1; j<unique.length; ++j) {
            if(unique[i] === unique[j])
            	unique.splice(j--, 1);
        }
    }
    console.log( unique );
	arr2 = unique;
	
	//배열 파싱
	$.each(arr2, function(i,v){
		html += '<div class="box">';
		html += '<span class="name">'+ v +'<button type="button" class="del" onclick="delFunc(this);">'+ v + ' 삭제</button></span>';
		html += '</div>';
	});
	$('.boxes').append( html );
});

function delFunc(btn){
	//선택된 문자열에서 특정 문자삭제
	var selectedDelTxt = $(btn).text().replace('삭제','').trim();
	//추가된 배열에서 선택 문자검색후 삭제
	var delIdx = arr2.indexOf( selectedDelTxt  );
	if( delIdx > -1 ){
		arr2.splice( delIdx, 1 );
	}
	arr2.sort();

	$('.boxes').html('');
	html = '';

	//배열 파싱
	$.each(arr2, function(i,v){
		html += '<div class="box">';
		html += '<span class="name">'+ v +'<button type="button" class="del" onclick="delFunc(this);">'+ v + ' 삭제</button></span>';
		html += '</div>';
	});
	$('.boxes').append( html );


	var releseIdx = arr1.indexOf( selectedDelTxt );
	console.log(releseIdx);
	if( releseIdx > -1 ){
		$('.checkboxes .checkbox input[name=chk]:checked').eq(releseIdx).prop('checked',false);
		arr1.splice( releseIdx, 1 );
	}
	arr1.sort();
}

'WEB > 내맘대로 코딩' 카테고리의 다른 글

배열메서드 - 필터링[2]  (0) 2020.05.05
배열메서드 - 필터링[1]  (0) 2020.05.05
선택요소 추가 및 삭제  (0) 2020.04.20
css3 효과주기  (0) 2020.04.16
틀린그림찾기  (0) 2020.04.15
swiperjs - 앙케이트 설문지  (0) 2020.04.14