I am struggling with creating an editable text field using JavaScript
. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function createTextNode
.
My confusion lies in how to use the statement
addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));
to add an event for editing the text field. You can run the code snippets to see the result.
var school = new School(1);
function School(id) {
this.id = id;
Unload_School();
function Unload_School() {
var div = document.createElement("div");
div.id = "school";
var h1 = document.createElement("h1");
h1.id = "h1";
h1.style.color = "red";
var title = document.createTextNode("High School");
h1.appendChild(title);
// I use here but not work
addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));
var h3 = document.createElement("h3");
h3.style.color = "blue";
var subtitle = document.createTextNode("List Of Students:");
h3.appendChild(subtitle);
div.appendChild(h1);
div.appendChild(h3);
document.body.appendChild(div);
};
}
function addEvent(obj, evType, fn) {
try {
obj.addEventListener(evType, fn, false);
} catch (e) {}
try {
obj.attachEvent("on" + evType, fn);
} catch (e) {}
}
function edit(param) {
var elem = param;
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("value", elem.firstChild.nodeValue);
removeChildren(elem);
elem.appendChild(input);
input.focus();
input.select();
addEvent(input, "blur", function() {
removeChildren(elem);
elem.appendChild(document.createTextNode(input.value));
});
}
function removeChildren(param) {
for (var i = 0, elem; elem = param.childNodes[i]; i++) {
elem.parentNode.removeChild(elem);
}
}
#school {
display: inline-table;
vertical-align: middle;
text-align: left;
}
#h1 {
font-size: 50px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans - serif;
}
<!DOCTYPE html>
<html lang="pt-PT">
<head>
<meta charset="UTF-8">
<title>High School</title>
</head>
<body>
<div id="school"></div>
</body>
</html>