So right now i have the following in my page:
where it consists of a dropdown menu and an input text field. So what I want is to create a JSON formatted object in javascript from the HTML elements above so I would get something like:
myObj = {
Name: Jake,
Address: 51 Lake District
}
However the method I'm using right now is sort of inefficient where i did it like:
var myObj = {
[document.getElementById("drop1").value]:document.getElementById("n_in").value,
[document.getElementById("drop2").value]:document.getElementById("a_in").value,
}
console.log(JSON.stringify(myObj))
I'm not entirely sure if this is a good way of doing it, but in the future if i were to add another set of fields like a "Country" dropdown in the HTML, I would have to hard code another field into the variable above again.
Is this a good way of doing it?
var myObj = {
[document.getElementById("drop1").value]:document.getElementById("n_in").value,
[document.getElementById("drop2").value]:document.getElementById("a_in").value,
}
console.log(JSON.stringify(myObj))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="lst">
<div class = "ifield">
<select id = "drop1">
<option value = "Name">Name</option>
</select>
<input type = "text" id = "n_in" value = "Jake">
</div>
<div class = "ifield">
<select id = "drop2">
<option value = "Address">Address</option>
</select>
<input type = "text" id = "a_in" value = "51 Lake District">
</div>
</div>
<script src = "test.js"></script>
</body>
</body>
</html>
