-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
75 lines (65 loc) · 2.44 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
document.addEventListener("DOMContentLoaded", function () {
// retrieve inputs and push of buttons
const userInput = document.getElementById("userInput");
const addItemButton = document.getElementById("addItem");
const itemList = document.getElementById("itemList");
const pickRandomButton = document.getElementById("pickRandom");
const result = document.getElementById("result");
let items = [];
addItemButton.addEventListener("click", function (event) {
event.preventDefault();
// Get the user input, trim any leading/trailing spaces, and split it into an array of values using commas as the separator
const values = userInput.value.trim().split(",");
// Loop through each value in the array
values.forEach((value) => {
// Remove any leading/trailing spaces and commas from the value
value = value.trim().replace(/,\s*/, "");
if (value) {
// Add the value to the items array
items.push(value);
const listItem = document.createElement("li");
// Set the text content of the list item to the value
listItem.textContent = value;
// Add the list item to the item list
itemList.appendChild(listItem);
// Clear the user input field
userInput.value = "";
console.log(items);
} else {
result.textContent = "No items to add.";
setTimeout(() => {
result.textContent = "";
}, 2000);
}
});
});
pickRandomButton.addEventListener("click", function (event) {
event.preventDefault();
// Check if there are any items to pick from
if (items.length > 0) {
// Generate a random index within the range of the items array
const randomIndex = Math.floor(Math.random() * items.length);
// Set the result text to display the randomly picked item
result.textContent = `Random pick: ${items[randomIndex]}`;
// Log the picked item to the console
console.log(`Picked item: ${items[randomIndex]}`);
} else {
result.textContent = "No items to pick from.";
setTimeout(() => {
result.textContent = "";
}, 2000);
}
});
clearButton.addEventListener("click", function (event) {
event.preventDefault();
itemList.innerHTML = "";
items = [];
result.textContent = "";
if (items.length == 0) {
result.textContent = "No items to clear.";
setTimeout(() => {
result.textContent = "";
}, 2000);
}
});
});