Strčil jsem <form>
soubor HTML do JS souboru, a pak addEventListener k této formě ale chyba dopadá:
Uncaught TypeError: Cannot read vlastnosti null (reading 'addEventListener').
Předpokládám, že je, protože tento JS souboru je spojen přímo do HTML souboru, což znamená, že JS by mohl být načten před <form>
.
Může někdo prosím, řekněte mi, jak vyřešit tento problém?
JS kódy jsou níže:
// skip to the input fields
$start.addEventListener('click', function(){
$chooseStory.remove()
const inputs = []
inputs.push(`
<form id="form">
<label>Provide The Following Words</lable>
`)
// assign words of stories to names and placeholders of inputs
// the input will automatically loop for as many as the words are
for (const word of stories[$index.value].words) {
inputs.push(`
<input type="text" name='${word}' placeholder="${word}">
`)}
inputs.push(`
<button type="submit" id="submit"> Read Story </button>
<code id="result"></code>
</form>
`)
const inputsField = inputs.join('')
$container.innerHTML += inputsField
})
// retrieve value of the form
const $form = document.getElementById('form')
$form.addEventListener('submit', function(e){
e.preventDefault()
})