Skip to content
Advertisement

script don’t work after fetching html file. Javascript only fires once

so I’m doing a project where I am fetching an HTML file and replacing the body content with the file I’m fetching.

So I have index.html and result.html. I have managed to get the content to switch based on the “matching search result in my input field”. But the problem I have is that the script from the .js file only fires once.

I don’t understand why that is. I want to be able to go back and forth between index.html and result.html

Here is my code for checking if the input field matches the file keyword:

JavaScript

And this is my code for fetching the HTML:

JavaScript

Advertisement

Answer

You are replacing your entire document with the contents of index/result.html, thus replacing your input, button and also scripts within the page.

My recommendation is to use a div container and update the contents of the div, rather than the innerhtml of the entire body of the document.

Here’s a working example:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement