Using Javascript Prototype, Need To Dynamically Add Div Onclick
(I am studying prototype in javascript..) I need to dynamically add student details on a div and keep adding more by using javascript prototype when a button(Add More) is clicked.
Solution 1:
Do not make addStudent function to prototype.
function Student(name, age, department) {
this.name = name;
this.age = age;
this.department = department;
}
Student.prototype.display = function() {
document.write("Name: " + this.name + ", age:" + this.age + "<br>")
};
function addStudent() {
var s1 = new Student();
s1.name = document.getElementById(name);
s1.age = document.getElementById(age);
s1.department = document.getElementById(department);
}
Solution 2:
I don't think you should extend the prototype of a Student, this way a new instance of a student could create another student.
I believe you could either create a department which could add students, or you could add an array with all students and filter it later as needed.
function Student(name, age, department) {
this.name = name;
this.age = age;
this.department = department;
}
var addButton = document.getElementById("addMore");
var allStudents = [];
addButton.addEventListener("click", function (e) {
var name = document.getElementById("name").value,
age = document.getElementById("age").value,
department = document.getElementById("department").value;
var student = new Student(name, age, department);
allStudents.push(student);
console.log(allStudents);
}, false);
Solution 3:
If we analyze your code, we see that you idea is that one student can add another student. I think its a wrong(maybe not). I think that department can add students(it more real in our life).
So code (core ideas):
var department = function(name){
this.name = name;
this.students = [];
}
var student = function(name, dep, age){
this.name = name;
this.dep = dep;
this.age = age;
// other logic
}
department.prototype.addStudent = function(){
// logic to get student data ( i write static information, you need write dynamic)
var name = "asdfasdf",
age = 12;
var n_student = new student(name, this.name, age);
this.students.push(n_student);
}
How to add studens:
var it_dep = new department("IT");
it_dep.addStudent();
it_dep.addStudent();
To access students in department
for(var i = 0; i < it_dep.students.length; i++){
document.write("Name: " + it_dep.students[i].name + ", age:" + it_dep.students[i].age + "<br>")
}
You can analyze demo.
Post a Comment for "Using Javascript Prototype, Need To Dynamically Add Div Onclick"