Thomas Thomas - 4 years ago 107
Javascript Question

How to add data to javascript object at run time

I tried to add data to js object at run time this way but getting error. Tell me where I made the mistake?

This line giving the problem

Persons.push(new Person(id:id,name:name,salary:sal));


Here is my code:

$(document).ready(function () {
$("#btnSave").click(function () {
var id,name,salary;
id=$("#txtID").val();
name=$("#txtName").val();
sal=$("#txtSal").val();
Persons.push(new Person(id:id,name:name,salary:sal));
return false;
});

$("#btnDelete").click(function () {
alert('delete');
return false;
});
});

var Persons = [];
var Person = function (id, name, salary) {
this.id = id;
this.name = name;
this.salary = salary;
};

Answer Source

You do not need to pass the parameter/argument names. Just pass the values to your Person constructor.

id = $("#txtID").val();
name = $("#txtName").val();
sal = $("#txtSal").val();
Persons.push(new Person(id,name,sal));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download