I have this html form to add data to a json array file
<head>
<script type="text/javascript" src="require.js"></script>
<script type="text/javascript" src="AddBook.js"></script>
</head>
<body>
<form id="add">
<input type="text" id="isbn" name="isbn">
<br>
<input type="text" id="title" name="title">
<br>
<input type="text" id="author" name="author">
<br>
<input type="text" id="issued" name="issued">
<br>
<input type="submit" name="submit">
</form>
<script>
var x = document.getElementById("add");
var isbn = x.elements[0].value;
var title = x.elements[1].value;
var author = x.elements[2].value;
var issued = x.elements[3].value;
write(isbn,title,author,issued);
</script>
and below is the AddBook.js
function write(isbn, title, author, issued) {
const fs = require(['fs'], function (fs){
const data = fs.readFileSync('js/book.json');
let jsonStr = data.toString();
const obj = JSON.parse(jsonStr);
obj.books.push({
isbn,
title,
author,
issued,
});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
fs.truncate('js/book.json', 0, () => {
fs.writeFile('js/book.json', jsonStr, (err) => {
if (err) {
throw new Error(`Error writing file: ${err}`);
}
});
});
});
}
The problem is that the below script works as a standalone file but stops working as soon as it is used with the HTML. How can I make this script work with the form
Try adding a function to run on the submission on your form. Something like this:
<head>
<script type="text/javascript" src="require.js"></script>
<script type="text/javascript" src="AddBook.js"></script>
<script>
function writeToJSON(){
var x = document.getElementById("add");
var isbn = x.elements[0].value;
var title = x.elements[1].value;
var author = x.elements[2].value;
var issued = x.elements[3].value;
write(isbn,title,author,issued);
}
</script>
</head>
<body>
<form id="add" onsubmit="writeToJSON()">
<input type="text" id="isbn" name="isbn">
<br>
<input type="text" id="title" name="title">
<br>
<input type="text" id="author" name="author">
<br>
<input type="text" id="issued" name="issued">
<br>
<input type="submit" name="submit">
</form>
</body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.