I would like to know how could I create a form that when I click on submit button it will create an json file.
Create/Update json file using a form
js file:
const petInputs = document.getElementsByName("pet");
const buildBtn = document.getElementById("build");
buildBtn.addEventListener("click", buildJSON);
function buildJSON(){
// Defines `petsObj` for grouping information and `resultObj` for building result
const petsObj = {},
resultObj = { pet: [] };
// Groups information by pet id# (separates unique pets from each other)
for(let input of petInputs){
const type = input.dataset.type,
id = input.dataset.id;
if(!petsObj["id" + id]){ petsObj["id" + id] = {}; }
petsObj["id" + id][type] = input.value;
}
// Counts the number of unique pets
let petsCount = 0;
for(let pet in petsObj){ petsCount++; }
// Adds all pets to the `pet` property of the `json` object
for(let i = 0; i < petsCount; i++){ resultObj.pet.push(petsObj["id" + i]); }
// Prints and returns the JSON object
console.log(resultObj);
return(resultObj);
}
Html File:
<input name="pet" data-type="species" data-id="0" value='Dahut'>
<input name="pet" data-type="name" data-id="0" value='Hypatia'><br />
<input name="pet" data-type="species" data-id="1" value='Felis Stultus'>
<input name="pet" data-type="name" data-id="1" value='Billie'><br />
<button id="build">Build JSON</button>
Refer to this for more:https://stackoverflow.com/a/57218815
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.