I have this function and I want to add this items in my arraylist. I know data.push(...) is not correct, so what it's the correct way?
function addinfo(data) {
var id = document.getElementById("courseid").value;
var nm = document.getElementById("name").value;
var yr = document.getElementById("year").value;
var syll = document.getElementById("syllabus").value;
var sem = document.getElementById("semester").value;
var teach = document.getElementById("teaching").value;
data.push(id,nm,yr,syll,sem,teach);
}
var data = [
{
courseid: "1",
name: "Artificial Intelligence",
year: "2021",
syllabus: "3",
semester: "2",
teaching: "Johan"
}
]
CodePudding user response:
I assume you want to push all these values as an object into the data array. You could achieve that by doing the following. By giving the variables the same name as the keys in the object you can leave that out.
var data = [
{
courseid: "1",
name: "Artificial Intelligence",
year: "2021",
syllabus: "3",
semester: "2",
teaching: "Johan"
}
]
function addinfo(data) {
var courseid = document.getElementById("courseid").value;
var name = document.getElementById("name").value;
var year = document.getElementById("year").value;
var syllabus = document.getElementById("syllabus").value;
var semester = document.getElementById("semester").value;
var teaching = document.getElementById("teaching").value;
data.push({courseid,name,year,syllabus,semester,teaching});
}
CodePudding user response:
Try this:
function addinfo(data) {
data.push({
courseid: document.getElementById("courseid").value,
name: document.getElementById("name").value,
year: document.getElementById("year").value,
syllabus: document.getElementById("syllabus").value,
semester: document.getElementById("semester").value,
teaching: document.getElementById("teaching").value
});
}