I'm trying to create a list which I can edit/update. I'll need to be able to store the list information in a variable of some sort and display the information on a HTML page.
My attempt is in the jsbin below.
JSBIN
https://jsbin.com/luxobineze/edit?html,js,console,output
So with that code, I'd like to:
- Add names by filling in the form and clicking "Add Name"
- Click [Edit] which will fill the form with the name that is to be edited
- Click Update to update the global variable "names" (If I can do this, then I should be able to update the HTML's "List of Names" as well)
I'm not sure what to do in the updateName function since I'm not sure how to pass the relevant arguments into it in order to update the correct list item. Do I need to use more global variables to keep track of the list item that's being edited? Or is there a better, more standard way of coding this?
The code in the jsbin is here:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Name: <input type="text" id="name-input"><br>
<button id="add-name" class="button">Add Name</button>
<button id="update" class="button">Update</button>
<div id="list">List of Names</div>
</body>
</html>
JavaScript
// global variable storing the list of names
var names = [];
function addName() {
var name = document.getElementById("name-input").value;
var list = document.getElementById("list");
if(name) {
names.push("name");
var wrapper = document.createElement("div")
wrapper.setAttribute("id", name)
var div_name = document.createElement("div");
div_name.appendChild(document.createTextNode(name))
var div_edit = document.createElement("div")
div_edit.appendChild(document.createTextNode("[edit]"))
div_edit.addEventListener("click", editName)
wrapper.appendChild(div_name)
wrapper.appendChild(div_edit)
list.appendChild(wrapper)
}
}
function editName() {
// Fill the input box with the name that you want to edit
var name = this.parentElement.getAttribute("id")
document.getElementById("name-input").value = name;
}
function updateName() {
var new_name = document.getElementById("name-input").value
// How do I update the global variable "names"?
}
document.getElementById("add-name").addEventListener("click", addName)
document.getElementById("update").addEventListener("click", updateName)
Edit
I ended up using some global variables to keep track of which item was currently selected: https://jsbin.com/zupawesifu/1/edit?html,js,console,output