The page is getting reset on submitting form after a while in HTML, javascript

In the HTML page I am creating, I have two url inputs. One for website and one for Image url. The link and the image at the url will be displayed. But when I submit, the page resets after few seconds after displaying the result. I am attaching my minimum reproducible code here. When only one of the inputs is https then it works not otherwise. Why it is behaving like this. There is no error also.
HTML file

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>demo</title>
<script type = "text/javascript" src="script.js"></script>
<body>
<form>
<label for="Website" >Website</label>
<input type="url"  id="Website" >
<label for="ImageLink" >Image Link</label>
<input type="url"  id="ImageLink" >
<button type="submit"  onclick="displayDetails()" id="submit">Submit</button>
</form>
<table id="display">
<tr>
    <th>Description</th>
    <th>Image</th>
</tr>
</table>
</body>
</html>

The script is as follows:
script.js:

var row  = 1;
var submit = document.getElementById("submit");
submit.addEventListener("submit",displayDetails);

function displayDetails(){
var website = document.getElementById('Website').value;
var imageSrc = document.getElementById('ImageLink').value;
var display = document.getElementById("display");
var Row = display.insertRow(row);
var cell = Row.insertCell(0);
var cell2 = Row.insertCell(1);
web = website.link(website);
cell.innerHTML =  web ;
img  =  document.createElement("img");
img.src = imageSrc;
cell2.appendChild(img);
row++;
}

If i enter random website name without https, then it works but not when both are valid https sites.

>Solution :

That is because whenever a form is submitted, a refresh event is triggered by default. You have to prevent this behavior. Update your code as follows.

Pass in parameter event to your function.

<button type="submit onclick="displayDetails(event)" id="submit">Submit</button>

Also, you have to update your JavaScript function as follows

function displayDetails(e) {
  e.preventDefault();
  var website = document.getElementById("Website").value;
  var imageSrc = document.getElementById("ImageLink").value;
  var display = document.getElementById("display");
  var Row = display.insertRow(row);
  var cell = Row.insertCell(0);
  var cell2 = Row.insertCell(1);
  web = website.link(website);
  cell.innerHTML = web;
  img = document.createElement("img");
  img.src = imageSrc;
  cell2.appendChild(img);
  row++;
}

Notice that the parameter event is received as e and the default behaviors are prevented by e.preventDefault()

Leave a Reply