I have a form with CSS, javascript and HTML in a file. When a user clicks on a button, I want to load the contents of the file into my page so the user can complete the form. I want to do this to save data since my users will only use this maybe 5% of the time.
I have a fetch request that calls the file and loads it in.
fetch('../templates/form.php/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify({form:true}),
})
.then(resp => resp.text())
.then(response => {
document.querySelector('body').insertAdjacentHTML('beforeend',response);
})
.catch(function(error){ console.log(error); });
HTML file (simplified)
<style>
#form{
height:100%;
width:100%;
position: absolute;
}
#submit{
width:60px;
height:30px;
}
</style>
<div>
<script>
window.addEventListener("load", function() {
document.getElementById("submit").addEventListener("click", function() {
console.log('form submitted');
});
});
</script>
<form id="form">
<input name="company-name">
<button id="submit"></button>
</form>
</div>
When I load the file with the fetch request, it works perfectly, the form is loaded in, and the CSS is applied. But I cannot get the onclick effects to work. If I put the console.log()
inside of the onclick=""
on the submit button, it works. How can I get the javascript to work? Its not practical to put javascript inside an onlcick
function in an element. I am looking for a solution that I can use all 3 datatypes in the same file.
Any ideas that would be awesome, thank you