Prevent page reloads w/ Ajax/JS (no jQuery): use event.preventDefault()


I’m trying to avoid page reloading when clicking a button, which prints some text in a textarea, in the home.html (index.html > login.html > home.html) page. This page contains a combobox, a textarea, and a button. The text is retrieved from using a condition.

I want to use Fetch in pure Javascript to prevent page reloading, instead of Ajax. However, I also need to be able to manage many comboboxes without splitting the code too much in the js file or js tag.

Is there a way to do this?

Yes, you can use the Fetch API in pure JavaScript to prevent page reloading when clicking a button. Here’s an example of how you can achieve this:

In your home.html file, you can add an event listener to the button that will make a fetch request to and update the textarea with the response. Here’s an example code snippet:

<!DOCTYPE html>
  <select id="combobox">
    <!-- options for combobox -->
  <textarea id="result" rows="5" cols="30"></textarea>
  <button id="submitButton">Submit</button>

    document.getElementById("submitButton").addEventListener("click", function() {
      var comboboxValue = document.getElementById("combobox").value;
      fetch("/path/to/" + comboboxValue)
        .then(response => response.text())
        .then(data => {
          document.getElementById("result").value = data;
        .catch(error => {
          console.error("Error:", error);

In your file, you can retrieve the comboboxValue from the request parameters and return the desired text based on the condition. Here’s an example code snippet:

def your_view(request):
    combobox_value = request.GET.get("comboboxValue")
    # Perform your logic based on the combobox value
    if combobox_value == "option1":
        result = "Text for option 1"
    elif combobox_value == "option2":
        result = "Text for option 2"
        result = "Default text"
    return HttpResponse(result)

Make sure to replace /path/to/ with the actual URL that points to your file.

This way, when the button is clicked, the fetch request is made to and the response is used to update the textarea without reloading the page.