What is the reason behind JavaScript events causing a page refresh?

My code uses RegExp to search through an array of strings based on user input:

Clinica.prototype.pesquisarDoente = function ()
{
    var exp = document.getElementById("pesquisaInput").value;
    var lista = document.getElementById("listaDoentes");
    if (exp)
    {
        while (lista.firstChild)
        lista.removeChild(lista.firstChild);
        var patt = new RegExp(exp);
        var lenght = this.doentes.length
        for ( i = 0; i < length; i++)
        {
            if (patt.test(this.doentes[i].nome))
            {
                var option = document.createElement("option");
                option.appendChild(document.createTextNode(this.doentes[i].toString()));

                lista.appendChild(option);

            }
        }
    }

}

This functionality is called within an event:

var buttonPesquisa = document.createElement("input");
    buttonPesquisa.type = "submit";
    buttonPesquisa.value = "Search";
    buttonPesquisa.addEventListener('click', function () { cl.pesquisarDoente(this); });

However, when I click the button, it clears the select list and refreshes the page. Why does that happen?

Answer №1

The reason for the page appearing to refresh when you click a submit button is because the button triggers a submit event by default...

To prevent this behavior, you should use preventDefault() on the event.

Here's an example:

var searchButton = document.createElement("input");
    searchButton.type = "submit";
    searchButton.value = "Search";
    searchButton.addEventListener('click', function (e) { e.preventDefault(); searchFunction(this); });

Answer №2

Submit buttons are used to send form data.

When a form is submitted, the data is sent to the specified URI by the action attribute (or the current page if no action is specified) and the response is loaded as a new page.

Answer №3

Modify the button's type to 'button':

let searchButton = document.createElement("input");
    searchButton.type = "button";
    searchButton.value = "Search";
    searchButton.addEventListener('click', function () { myApp.searchPatient(this); });

Answer №4

Simply implement

var searchButton = document.createElement("button");
searchButton.type = "button";
// remaining code

This approach will prevent the page from automatically refreshing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

Execute function periodically using Vue.js

I have a requirement to update data periodically by calling a function in my Vue.js application. I am looking to call the 'listar()' method every 30 seconds and store the response in a property of vue js. If anyone can guide me on where to locat ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

Deciphering JSON using JavaScript

Looking to decode a URL using Javascript? let url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=drove&mode=driving&language=en&sensor=false"; fetch(url) .then(response => response.json()) .th ...

Display a button within a table depending on the content of adjacent cells

Below is the code snippet I'm currently working with: <tbody *ngIf="packages"> <tr *ngFor="let package of packages"> <td class='checkbox'> <label class="css-control css-co ...

Ways to resolve BuildJobExitNonZero issue on Digital Ocean

Hey everyone, this is my first time using Digital Ocean. I'm trying to deploy my app via Launch App, and my code is hosted on GitHub. However, when I try importing the code and building it, I'm encountering the following error that I don't u ...

A step-by-step guide on implementing lazy loading for a specific div section using either AJAX or Java

I'm facing an issue with a div section that contains numerous tables pulled from my database. The main problem here is that when the page loads, it takes a considerable amount of time to fully load all the content, causing a significant delay. Could ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

Sauce Labs encountering issues when running JavaScript code

Currently, I am using Selenium WebdriverJs along with Mocha to conduct tests on Sauce Labs via Travis CI. After isolating the issue without any project dependencies, I am seeking help. The interesting observation is that defining an additional object with ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

Alerting old session data following an AJAX request

After making an AJAX call that updates a $_SESSION variable, my <script> is supposed to echo out the new variable. However, it keeps alerting the old data even though the data is reaching the .php page and being stored in the session. I've attem ...

The carousel is failing to display two items on each slide

I've integrated a carousel library from npm into my project. However, I'm facing an issue where I need to display two cards in each slide within the carousel. Here's a snippet of my code: Catalog.js import React from 'react'; impo ...

Showing skeleton placeholders while waiting for the completion of an Array map function in React

I am currently working on a country list component that includes phone codes, country names, and flags. The use of the map() function is causing some delay in loading time. I am looking for a way to determine if the map() function has finished executing or ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...