Building an array in Javascript and filling a text area with the array and clearing it on button click.
To build an array in Javascript you need to have defined the array and then use push() to insert a value at the end of the array.
Javascript array push example:
let the_array = []; the_array.push('itemValue');
Clearing the array is done by setting the array back to empty: fruit_array = [];
Now a system to add values from a button into an array which will then populate the text area in its array form:
The jQuery:
let fruit_array = []; $(document).ready(function () { $(".add-btn").click(function () { var fruit = $(this).text(); fruit_array.push(fruit); $('#array-text-box').val(JSON.stringify(fruit_array)); }); $(".clear-btn").click(function () { $('#array-text-box').val('[]'); fruit_array = []; }); });
The HTML:
<div class="container"> <div class="card"> <div class="card-header"> <h1 class="text-center">Build an array</h1> </div> <div class="card-body"> <div class="row"> <div class="col-6 col-md-2"> <button type="button" class="btn btn-success btn-sm add-btn">Apple</button> </div> <div class="col-6 col-md-2"> <button type="button" class="btn btn-primary btn-sm add-btn">Banana</button> </div> <div class="col-6 col-md-2"> <button type="button" class="btn btn-success btn-sm add-btn">Lemon</button> </div> <div class="col-6 col-md-2"> <button type="button" class="btn btn-primary btn-sm add-btn">Lime</button> </div> <div class="col-6 col-md-2"> <button type="button" class="btn btn-success btn-sm add-btn">Orange</button> </div> <div class="col-6 col-md-2"> <button type="button" class="btn btn-primary btn-sm add-btn">Melon</button> </div> </div> <div class="row my-3"> <div class="col-12"> <textarea class="form-control" id="array-text-box" rows="3">[]</textarea> </div> </div> <div class="row"> <div class="col-12 text-center"> <button type="button" class="btn btn-danger btn-lg clear-btn">Clear the array</button> </div> </div> </div> </div> </div>