2

Currently developing a new website and looking to use jQuery's load() function to load content from different html pages into my main page.

load() works fine. Here's my current code. Main.html page in which content is loaded:

<div id="answer"></div>

Javascript with the load() function:

$(document).ready(function() {
    $("#answer").load( "game1content.html #p1Answer");

game1content.html content to load:

<div id="p1Answer">
    <p>Some text</p>
    <form id="answer1Form">
        <select name="answer1" id="answer1">
            <option value=""></option>
            <option value="1">Website 1</option>
            <option value="2">Website 2</option>
            <option value="3">Website 3</option>
            <option value="4">Website 4</option>
        </select>
        <button id="submitButton">SUBMIT</button>
    </form>
</div>

So it loads html correctly into the answer div. Perfect.

Now the challenge is that when I submit the form that's loaded, it refreshes the page. When I have the game1content content in the main.html file, instead of using the load() it doesn't reload and works fine. But if I use the load() function, it does reload and also changes the url.

Here's my function on submit:

$( "#answer1Form" ).submit(function(e) {
    e.preventDefault();
    console.log ("clicked");
});

I've tried Googling this issue, but can't find much. Also, tried changing .submit to onclick etc, but same result. Any ideas?

1
  • e.stopPropagation(); return false; Commented Jul 26, 2020 at 16:50

1 Answer 1

1

That's because when you call .load, it fetch the page content and adds DOM elements but not bind them to events, so the form behave like it should, refresh the page.

In order to prevent the form from refreshing you should listen to .submit() exactly like you do in game1content.html after the DOM elements are added.

Like this:

$("#answer").load( "game1content.html #p1Answer", function() {
  $( "#answer1Form" ).submit(function(e) {
    e.preventDefault();
    console.log("clicked");
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! Thanks so much for your help, makes my day!
Any time :) Good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.