i need to show input value on page. when i press submit button value shows for a moment and then page refreshes immediately. i want the page not to resresh and show value. Also i would like to know why page is refreshing after submit button. Thank in advance!
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page 1</title>
<link rel="stylesheet" href="style.css">
<script src="index.js"></script>
</head>
<body>
<form>
<label for="name">Name:</label>
<input id="name" type="text">
<input type="submit" value="Send" onclick="myFunc()">
</form>
<p id="show_name"></p>
</body>
</html>
JAVASCRIPT CODE:
function myFunc(){
const obj = {
name : document.getElementById("name").value
}
document.getElementById("show_name").innerHTML = obj.name;
}
i already have tried event.preventDefault()
and it worked but i would like to know if there are another ways or i just have mistakes in code.
3
Answers
Submit button when click on it send a http request to the server and this protocol knows that for this type of request, the answer gived must refresh the web page before appear
HTTP, the Hypertext Transfer Protocol, is the foundation of the web, and it is what allows web browsers to communicate with web servers to request and receive web pages.
So, to stop page to refresh like you said, using the event.preventDefault() was good.
use button element instead of input element
or
and use e.preventDefault() in your Js code
When you set type="button", the button is considered a regular button and won’t trigger the form submission by default
If you use
event.preventDefault()
without passing any event this means you are using theevent
directly from the window object which is currently deprecated. It’s still supported by different browsers but I’d recommend to not rely on mozilla – more details.So it’s recommended to pass the
event
into the event handler function.Example: