Pressing the button element equipped with an event listener leads to the page being refreshed

I'm encountering an issue with my function in this JSFiddle

window.addEventListener("load", init, false);

function init() {
  let name = document.getElementById("name").addEventListener("blur", checkName, false);
  let startButton = document.getElementsByTagName("button")[0].addEventListener("click", startClicked, false);
}

function checkName(event) {
  const regEX = /^\d[A-Z]{2}\d{1,}K$/;
  let name = document.getElementById("name");
  let button = document.getElementsByTagName("button")[0];

  if (regEX.test(name.value)) {
    button.removeAttribute("disabled");
    button.setAttribute("enable");
  }
}

function startClicked(event) {
  let button2 = document.getElementById("choice1");
  button2.removeAttribute("disabled");

  let button3 = document.getElementById("choice2");
  button3.removeAttribute("disabled");

  showQuestion();
}

function showQuestion(event) {
  let question = document.getElementById('question');
  question.innerHTML = "Hello";

}
body {
  font-family: sans-serif;
  font-size: large;
}

form {
  text-align: center;
}

button {
  width: 300px;
  height: 100px;
  font-size: large;
}

form div {
  margin: 2em;
}

#report {
  display: none;
  position: absolute;
  top: 100px;
  left: 100px;
  background-color: lightgray;
  opacity: 0.9;
  padding: 3em;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <title>Exam p5>
  <script src="scripts/exam.js.pdf.js"></script>
  <script src="scripts/hands-off.js"></script>
  <link rel="stylesheet" href="style/style.css">
</head>

<body>
  <form>
    <div>
      <h1>Survey Tool</h1>
      <p>First enter a correct code: start with a number, followed by 2 capital letters, then 1 or more numbers and the code ends with a K. Press start to begin the survey...</p>
      <label for="name">Code: </label><input type="text" id="name" />
    </div>
    <button disabled>Start</button>
    <div>
      <p id="question">A question</p>
      <button id="choice1" disabled>Choice1</button>
      <button id="choice2" disabled>Choice2</button>
    </div>
  </form>
  <section id="report">
    <h1>Answers Overview</h1>
    <table>

    </table>
  </section>
</body>

</html>

The required code input is

1KK1K

The problem arises when the listener handler is triggered:

function startClicked(event) {
    let button2 = document.getElementById("choice1");
    button2.removeAttribute("disabled");

    let button3 = document.getElementById("choice2");
    button3.removeAttribute("disabled");

    showQuestion();
}

It causes an automatic page refresh back to the default state.

Note: I am unable to directly modify the HTML, all changes must be made through JavaScript.

Answer №1

The button element behaves like a form, causing it to refresh.

To address this issue, you have two options in JavaScript or HTML:

JavaScript:

  • Include event.preventDefault() at the start of your button handler function to prevent the button's default action, or

HTML:

  • Add type="button" to the button tag in the HTML because by default it acts as a 'submit' button according to MDN Web Docs

Here is an updated version of your code on JSFiddle.

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

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...

Measuring the pixel distance of scrolling on a page with overflow hidden

I am trying to implement a functionality where a class is toggled for the body element on a page with hidden overflow and single screen, based on the amount of scroll. However, there is a challenge: the scrolling behavior involves animation rather than act ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8 I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide. Data Object Structure data: functio ...

Tips for making an interactive slider using JQuery

I need to create dynamic sliders within tabs that can change content dynamically. My development platform is ASP.NET MVC 5 and I'm using JSON data format. What's the best way to implement this dynamic slider feature for each tab? <div class ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...

Recently updated to the latest versions of Angular, AngularCLI, and Rxjs (version 6), however encountering an error stating "Property 'take' does not exist on type 'Observable'"

Recently, I made the decision to update my Angular5 project to Angular6 and upgraded all dependencies along with it (such as rxjs now at version 6 and angular-cli). However, I have encountered a problem that is proving difficult to resolve: ERROR in src/ ...

Utilize Launchdarkly in React by incorporating it through a custom function instead of enclosing it within

Currently, I am adhering to the guidelines outlined by launchdarkly. Following the documentation, I utilized the following code snippet: import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk'; (async () => { const LDProvider = a ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

Collapse the sidebar using React when clicked

Just beginning to learn about React and I'm trying to figure out how to toggle the open/closed state of a react-pro-sidebar component using a click event: export default function MaterialLayout(props) { const { children } = props; const classes = us ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

Cross-Origin Resource Sharing (CORS) for enabling the remote inclusion of JavaScript

I have a unique javascript widget that is designed to be embedded from an external server (e.g. ) The javascript, which contains a simple alert('hello'), is generated by a php script. Upon execution, I include a header like this: <?php heade ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Papaparse and vfile not functioning properly - Output appears jumbled

I recently posted a question on Stack Overflow about parsing large CSV files, the issue can be found here. The problem involves reading a CSV file and converting it into a table format. I attempted to use the code provided in one of the responses, but unfo ...

AngularJS is not triggering the $watch function

I'm facing an issue with the $scope.$watch function, as it's not being triggered when expected. In my HTML document, I have a paginator using bootstrap UI: <pagination total-items="paginatorTotalItems" items-per-page="paginatorItemsPerPage" ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...