Reputation: 531
I have very little experience with Javascript.
My goal is to build a table from an array, and allow the user to delete items from the array as needed. I wanted to have a "delete" button next to each array item that is shown.
I'm open to other ideas of how to accomplish this. My code is here:
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
LLen = LargeList.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + LargeList[i] + "</li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = LargeList.join("/ ");
}
The target HTML:
<body>
<div>
<select id="LargeItems">
<option></option>
<option>LMIS</option>
<option>ARMC</option>
<option>BNCH</option>
</select>
<input type="button" onclick="AddLargeItem()" id="AddLargeItem" value="ADD LARGE" />
<span><p id="LargeCount"></p></span>
</div>
<p id="random"></p>
<p id="LargeInventory"></p>
</div>
Upvotes: 0
Views: 1132
Reputation: 27793
I wanted to have a "delete" button next to each array item that is shown
To achieve your above requirement, you can modify the code as below.
<script>
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
PopulateList(LargeList);
}
function PopulateList(arr) {
LLen = arr.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + arr[i] + "<input type='button' onclick='Delitem(" + i + ")' value='Delete' /></li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = arr.join("/ ");
}
function Delitem(index) {
LargeList.splice(index, 1);
PopulateList(LargeList);
}
</script>
Test Result
Upvotes: 1
Reputation: 55
There is two ways I can think of to do this.
num one: assign the elements you want to delete and id ex: then use javascript to append the elements with your list. then onclick="remove('list')" and make a function like this
function remove(id){getElementById(id).remove()}
num two: if you just want to use javascript def your list then get an integer from the user and use my something like this
index = getElementById('foo').value;
my_list = my_list[:foo] + my_list[foo+1:];
document.write(my_list);
Upvotes: 0