[HTML5, Javascript, Jquery] Add item from array to list when button is clicked in jQuery

[Qustion]

I'm building a UI where a user can select from a list, include the selection in an array and then display the array in another list. I'm very close. However, every time I add an item to the list it repeats items.

How do I clear the list before it builds from the array again.

You can see how it works and my code here:

 

$(document).ready(function(){
    var a = [];
    
  $(".btn").click(function(){
	a.push($(this).next("span").text());
	$(this).closest("li").hide();
    $( "#s" ).text( a.join( " " ) );

    $.each(a, function(i){
        var cList = $('ul.mylist');
    	var li = $('<li/>')
        	.addClass('ui-menu-item')
            .attr('role', 'menuitem')
            .appendTo(cList);
        var aaa = $('<a/>')
           	.addClass('ui-all')
           	.text(a[i])
            .appendTo(li);      
        });   
    });
});
<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Selector</title>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
   </head>
   <body>
      <h2>List of Options</h2>
      <ul>
         <li><button class="btn">Select</button><span>One</span></li>
         <li><button  class="btn">Select</button><span>Two</span></li>
         <li><button class="btn">Select</button><span>Three</span></li>
         <li><button class="btn">Select</button><span>Four</span></li>
      </ul>
      <h2>List of Selections</h2>
      <ul class="mylist"> 
      </ul>
      <h2>Array</h2>
      <div>Array of Selected Items to Send to DB:</div>
      <span ID="s"></span>
   </body>
</html>

[Answer]

You have to empty the Ul html first because you make a each function which append all values of array again and again so it repeat the values. You can see live demo here :- 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

$(document).ready(function(){
var a = [];

 

 $(".btn").click(function(){
  var obj = $(this);
	a.push(obj.next("span").text());
  console.log(a);
	obj.parent().hide();
   $( "#s" ).text( a.join( " " ) );
$('ul.mylist').html("");
    $.each(a, function(i){
        var cList = $('ul.mylist');
    	var li = $('<li/>')
        	.addClass('ui-menu-item')
            .attr('role', 'menuitem')
            .appendTo(cList);
        var aaa = $('<a/>')
           	.addClass('ui-all')
           	.text(a[i])
            .appendTo(li);      
        });   
    });
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selector</title>  
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>
<h2>List of Options</h2>
<ul>
    <li><button class="btn">Select</button><span>One</span></li>
    <li><button  class="btn">Select</button><span>Two</span></li>
    <li><button class="btn">Select</button><span>Three</span></li>
    <li><button class="btn">Select</button><span>Four</span></li>
</ul>
<h2>List of Selections</h2>
<ul class="mylist"> 
</ul>
<h2>Array</h2>
<div>Array of Selected Items to Send to DB:</div>
<span ID="s"></span>
</body>
</html>

[출처] https://stackoverflow.com/questions/41775694/add-item-from-array-to-list-when-button-is-clicked-in-jquery

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
214 [HTML] Div 를 새창 팝업으로 띄우기 졸리운_곰 2022.09.09 451
213 [JWT} [WEB] JWT(Json Web Token)란? 개념 정리 및 예제 file 졸리운_곰 2022.07.15 516
212 [HTML 디자인] 웹페이지 가로 모드/세로 모드 인식하기 file 졸리운_곰 2022.02.14 314
211 [web개발] [jQuery] Select박스 option 값 선택하기 졸리운_곰 2021.10.20 651
210 [web개발][javascript][JQuery] textarea 값 설정및 값 가져오기 졸리운_곰 2021.10.19 441
209 [web개발][javascript] javascript - 주소의 파라미터값 변수로 받기 졸리운_곰 2021.10.19 332
208 [javascript][jquery] jQuery 이벤트 중복 방지 - jQuery에서 이벤트 핸들러를 제거하는 가장 좋은 방법은 무엇입니까? 졸리운_곰 2021.09.07 232
207 [javascript] How to append HTML code to a div using JavaScript ? file 졸리운_곰 2021.09.07 381
206 [javascript][jQuery] 제이쿼리(jQuery) 선택자 - #1 file 졸리운_곰 2021.09.07 570
205 [html] div안의 컴포넌트가 브라우저 줄이면 자동 개행되는 것 방지 졸리운_곰 2021.09.07 276
» [HTML5, Javascript, Jquery] Add item from array to list when button is clicked in jQuery 졸리운_곰 2021.06.01 739
203 [Javascript, ajax] <jQuery>Ajax, json(제이손) 파싱해서 가져오기 졸리운_곰 2021.05.17 492
202 [Javascript, ajax] XMLHttpRequest, jQuery Ajax 예제 file 졸리운_곰 2021.05.17 597
201 [javascript] Javascript JSON.parse(), JSON.stringify() 사용하는법 졸리운_곰 2021.05.17 367
200 [JAVASCRIPT에서 session 값 가져다 쓰는 법] 가져오는 법, string data type과 비교하는 법 졸리운_곰 2021.05.14 2592
199 [javascript] 다른 도메인으로 AJAX을 위한 Access-Control-Allow-Origin 졸리운_곰 2021.05.14 675
198 [javascript] html 로드시 자동실행 javascript : 자동 실행 함수 (window.onload, $(document).ready()) 졸리운_곰 2021.05.14 635
197 [javascript] 순수 javascript로 동기 ajax, Sync ajax without jquery? 졸리운_곰 2021.05.14 989
196 [javascript][hello world]자바스크립트] 문자열 출력 함수, 텍스트 쓰기; HTML-JavaScript Print String 졸리운_곰 2021.05.14 597
195 [HTML][HTML5] [HTML을 배워보자] 구역을 만드는 태그(header, nav, aside, section, article) file 졸리운_곰 2021.04.28 302
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED