I’m trying to learn about user-defined objects in JavaScript. Specifically, I’m trying to create a method of a user-defined object that will use the document.getElementById("holder") and append to it using document.createElement('p') and append to it a text node with document.createTextNode("text").
Currently, my method is not doing that. I’ve tested the method and it is getting called, but nothing appears in the page from the item.appendChild(otheritem). I’ve looked through other posts but none explained my situation, at least that I am aware of. My code is below.
<html>
<head>
<title></title>
<script type="text/javascript">
function Person(fn, ln) {
this.fname = fn;
this.lname = ln;
}
Person.prototype.getFullName = function () {
var myPara = document.createElement('p');
var strFullName = document.createTextNode("super");
myPara.appendChild(strFullName);
var objHolder = document.getElementById("objHolder");
objHolder.appendChild(myPara);
};
function getSome() {
var fN = document.getElementById("fname").value;
var lN = document.getElementById("lname").value;
var Myperson = new Person(fN, lN);
alert(Myperson.fname);
Myperson.getFullName();
}
</script>
</head>
<body>
<form id="holder">First Name:
<input id="fname" type="text" width="40" />Last Name:
<input id="lname" type="text" width="40" />
<button id="buildObj" value="Click" onClick="getSome()">Click</button>
</form>
<div id="objHolder"></div>
</body>
</html>
Any help or recommendations would be appreciated. Also, if I’m missing a key concept, knowing that would be good too.
Thanks,
Mike
The append works but at the same time the form is submitted, so it redirects to another page. You need to cancel the natural browser behaviour of submitting the form via
return falsein an event handler for thesubmitevent.The more elegant method is to use the
eventobject and then callevent.preventDefaultbut due to browser inconsistencies it takes a lot of code to get it right.. so for this basic example,onsubmitandreturn falseshould suffice.