Skip to content

Instantly share code, notes, and snippets.

@bzdgn
Last active January 13, 2016 23:43
Show Gist options
  • Save bzdgn/a37f93e7ac9d143fc041 to your computer and use it in GitHub Desktop.
Save bzdgn/a37f93e7ac9d143fc041 to your computer and use it in GitHub Desktop.
JavaScript Setter Method Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
input[type=text]{
width: 100px;
}
.inputButton{
width: 100px;
}
.loneButton{
width: 204px;
}
</style>
</head>
<body>
<h1>Object Methods Example #2</h1>
<br>
<h3>Internal Setter Method</h3>
<table>
<tr>
<td>
New Name:
</td>
<td>
<input id="inputName" type="text" required><button class="inputButton" onclick="changeName()">Change Name</button>
</td>
</tr>
<tr>
<td/>
<td>
<button class="loneButton" onclick="fullName()">Full Name of Person</button>
</td>
</tr>
<tr>
<td/>
<td>
<button class="loneButton" onclick="resetAll()">Reset All</button>
</td>
</tr>
</table>
<br>
<p id="output">Person: </p>
<p id="fullNameId">Person Full Name : </p>
<script>
"use strict";
var outputPre01 = document.getElementById("output").innerHTML;
var outputPre02 = document.getElementById("fullNameId").innerHTML;
var inputName = document.getElementById("inputName");
var person; // declare person
prepare(); // init person & student
// fullName
function fullName() {
var output = document.getElementById("fullNameId");
var outTxt = "<br>";
outTxt = person.fullName();
writeToOutput( output, outputPre02 + outTxt );
}
// changeName
function changeName() {
if( inputName.validity.valueMissing ) {
alert("An input must be entered");
} else {
var newName = inputName.value;
person.changeName(newName);
}
}
// reset Content
function resetAll() {
var output = document.getElementById("fullNameId");
writeToOutput( output, outputPre02 );
prepare();
}
// prepare
function prepare() {
inputName.value = "";
preparePerson();
}
// prepare person
function preparePerson() {
var output = document.getElementById("output");
person = {
id : "1017",
firstName : "Levent",
lastName : "Divilioglu",
age : 33,
birthDate : new Date("1982-01-24").getTime(),
eyeColor : "brown",
printAll : function() { return JSON.stringify(this) },
fullName : function() { return this.firstName + " " + this.lastName; },
changeName : function(newName) { this.firstName = newName }
};
writeToOutput( output, outputPre01 + person.printAll() );
}
// writer
function writeToOutput(outId, msg) {
outId.innerHTML = msg;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment