I have a form that has a submit button in it somewhere.
However, I would like to somehow \'catch\' the submit event and prevent it from occurring.
Is there s
You can add eventListner to the form, that preventDefault()
and convert form data to JSON as below:
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
const handleFormSubmit = event => {
event.preventDefault();
const data = formToJSON(form.elements);
console.log(data);
// const odata = JSON.stringify(data, null, " ");
const jdata = JSON.stringify(data);
console.log(jdata);
(async () => {
const rawResponse = await fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: jdata
});
const content = await rawResponse.json();
console.log(content);
})();
};
const form = document.forms['myForm'];
form.addEventListener('submit', handleFormSubmit);