An array example

Toggle class name on click in jQuery

by Jonathon Mascorella

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container" id="banner-message">
  <div class="row mt-3">
    <div class="col">
      <h2>A little example</h2>
    </div>
    <div class="col">
      <p>
        Let's add, remove and clear an array of items!
      </p>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <div class="btn-group mt-5" role="group" aria-label="Basic example">
        <button type="button" class="btn btn-secondary" id="addItem">Add item</button>
        <button type="button" class="btn btn-secondary" id="removeItem">Remove item</button>
        <button type="button" class="btn btn-secondary" id="clearAll">Clear Array</button>
      </div>
    </div>
  </div>
  <div class="row mt-1">
    <div class="col">
      <label for="numberToRemove">Specific item to remove</label>
      <div class="form-group">
        <input type="text" id="numberToRemove">
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <span id="arrayOutput"></span>
    </div>
  </div>
</div>

JavaScript

// standard Array
someArray = [];

// JSON = Javascript Object Notation
userData = {
	"FirstName": "Jonathon", 
  "Age": 37,
  "Phone numbers": [049320495, 0485830284, 027847382]
  };

$("#addItem").click(function() {
  //do something
  someArray.push(someArray.length+1);
  console.log(someArray);
  printArray();
});

$("#removeItem").click(function() {
  //do something
  //someArray.pop();
  //someArray.shift();
  //console.log(someArray);
  
  // Get the number to remove
  numToRemove = $("#numberToRemove").val();
  
  // Parse as an INTEGER
  numToRemove = parseInt(numToRemove);
  
  //Get the index of the item to remove
  var index = someArray.indexOf(numToRemove);
  
  //Sorry - needed to make sure it wasn't -1
  if (index != -1) {
  	//Remove the item
  	someArray.splice(index, 1);
    console.log(someArray);
  }else {
  	window.alert("That item " + numToRemove + " is not in the array!");
  }
  
  //Print the array
  printArray();
  clearInputValue();
  //DEBUG
  //console.log(someArray);
});

function clearInputValue () {
	$("#numberToRemove").val("");
}

$("#clearAll").click(function() {
  //do something
  let theLengthOfArray = someArray.length;
  for(var i = 0; i < theLengthOfArray; i++){
  	someArray.pop();
    printArray();
  }
});

function printArray() {
	$("#arrayOutput").text("");
  // for some reason the var item wasn't working
  for(i = 0; i < someArray.length; i++) {
  	console.log(someArray[i]);
  	$("#arrayOutput").append(someArray[i]);
  }
}