[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

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
» [HTML5, Javascript, Jquery] Add item from array to list when button is clicked in jQuery 졸리운_곰 2021.06.01 6
444 [Javascript, ajax] <jQuery>Ajax, json(제이손) 파싱해서 가져오기 졸리운_곰 2021.05.17 40
443 [Javascript, ajax] XMLHttpRequest, jQuery Ajax 예제 file 졸리운_곰 2021.05.17 39
442 [javascript] Javascript JSON.parse(), JSON.stringify() 사용하는법 졸리운_곰 2021.05.17 16
441 [JAVASCRIPT에서 session 값 가져다 쓰는 법] 가져오는 법, string data type과 비교하는 법 졸리운_곰 2021.05.14 2131
440 [javascript] 다른 도메인으로 AJAX을 위한 Access-Control-Allow-Origin 졸리운_곰 2021.05.14 46
439 [javascript] html 로드시 자동실행 javascript : 자동 실행 함수 (window.onload, $(document).ready()) 졸리운_곰 2021.05.14 123
438 [javascript] 순수 javascript로 동기 ajax, Sync ajax without jquery? 졸리운_곰 2021.05.14 13
437 [javascript][hello world]자바스크립트] 문자열 출력 함수, 텍스트 쓰기; HTML-JavaScript Print String 졸리운_곰 2021.05.14 24
436 [WebGL/WebGPU] 파이어폭스에서 WebGPU 맛보기 A Taste of WebGPU in Firefox file 졸리운_곰 2021.05.02 56
435 [HTML][HTML5] [HTML을 배워보자] 구역을 만드는 태그(header, nav, aside, section, article) file 졸리운_곰 2021.04.28 40
434 [wordpress] WPForms 워드프레스 폼빌더 사용법 file 졸리운_곰 2021.04.25 1256
433 [JWT] JWT 토큰 기반 인증 file 졸리운_곰 2021.04.24 64
432 [JWT] JWT 서버 인증 file 졸리운_곰 2021.04.24 16
431 [JWT] REST JWT(JSON Web Token)소개 - #2 node.js에서 JWT 사용하기 file 졸리운_곰 2021.04.24 14
430 [JWT] JWT(JSON Web Token)을 이용한 API 인증 - #1 개념 소개 file 졸리운_곰 2021.04.24 32
429 [WASM][WebAssembly] The Top 81 Emscripten Open Source Projects 졸리운_곰 2021.04.19 48
428 [wordpress][워드프레스] 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.04.15 12
427 [JavaScript] How to Write a Simple Interpreter in JavaScript file 졸리운_곰 2021.04.13 175
426 [WebAssembly][WSAM] Blazor와 WebAssembly 소개 file 졸리운_곰 2021.03.28 91
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED