Form submit input not running my onClick function - javascript

I have created a simple login form, and want to run a js function once the form is submitted. However, nothing happens when I click submit.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CARD GAME</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="index.js"></script>
<form>
Username: <input type="text" id="htmlUsername"><br><br>
Password: <input type="password" id="htmlPassword"><br>
<input type="submit" onclick="login()">
</form>
</body>
</html>
JS:
function login(){
console.log("here")
}

Is the browser window reloaded when you press the submit button? If yes, then your form is indeed submitted.
You don't see the output of console.log statement because, by default, browser window is reloaded on form submission. You can disable this default behaviour using event.preventDefault()
HTML:
<form>
Username: <input type="text" id="htmlUsername"><br><br>
Password: <input type="password" id="htmlPassword"><br>
<input type="submit" onclick="login(event)">
</form>
JS:
function login(event){
event.preventDefault();
console.log("here")
}
Suggested improvements:
Instead of using onclick attribute on the button element, use .addEventListener() to add the click event listener on the button.
Move the script element to just before the closing body tag.
Alternative Solution
Another way is to preserve the logs. In the "Netowork" tab of browser developer tools, check the "preserve logs" checkbox input. Doing this will preserve the output of console.log statement even if the browser window is reloaded on form submission.
For details of how to enable this option in developer tools, visit:
How to enable “Preserve Log” in Network tab in Chrome developer tools by default?

If you want to perform certain actions by clicking on submit, then declare event onsubmit inside the form tag. Like this:
<form onsubmit="login(event);">
...
And add disabling the default behavior - event.preventDefault().
function login(event){
event.preventDefault();
console.log("here")
}
But I do not advise you to declare js events inside html tags. Since this will lead to bad consequences.
Try it:
let form_submit = document.querySelector('form');
form_submit.onsubmit = function(event) {
event.preventDefault();
console.log("here");
}
And remove onclick="login()" from input submit. Here:
<input type="submit" onclick="login()">

I see two things here for now.
Put your code which includes js file at the bottom of your HTML, just above closing body tag.
<script src="index.js"></script>
Check if your JavaScript file is called index.js

Replace <input type="submit" onclick="login()"> with <button type="button" onclick="login()">Login</button>
Add an ID to your form: <form id="myform"> ...
in your JS do:
function login(){
alert("here");
document.querySelector("#myform").submit();
}

Related

Page seems to refresh when I submit an HTML form and the console is wiped [duplicate]

I'm creating a login form and in that if any input is wrong then i want to stay on the same page and notify the client to enter the correct input
I want to stay on this page http://localhost:8080/loginpage/ but after every click i'm redirected to http://localhost:8080/loginpage/?UserName=UserName&pword=&ConfirmPassword=&Email=Email&FirstName=First+Name&LastName=Last+Name&cars=male&Signup=Signup .
I have written a code for this but it does not seem to work.
if(t!==0)
{
var er="Email-id already exists";
window.location.reload(false);
document.getElementById("nemail").value=er;
document.getElementById("username").value=username;
document.getElementById("pword").value="";
document.getElementById("confpwd").value="";
document.getElementById("fname").value=fname;
document.getElementById("lname").value=lname;
document.getElementById("gender").value=gender;
}
I have tried to use several other methods like
window.location.replace('/loginpage/');
window.location.href="/loginpage/index.html";
But none of them works.
Please help!
There are two ways to prevent a form to submit.
Set form onsubmit="return false".
Register a submit event on a from. In the callback call event.preventDefault();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>1 way to prevent form to submit via onclick attribute</h2>
<form action="#submit-from-1-way" onsubmit="return validate(this)"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<h2>2 way to prevent form to submit via submit event</h2>
<form id="form" action="#submit-from-2-way"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<script>
console.log(location.href+'#'+location.hash+'?'+location.search);
function validate(form) {
return $(form).find('input').val();
}
$('#form').submit(function (e) {
if (!validate(this)) e.preventDefault();
});
</script>
You can use preventDefault() on the click event for a given html object. This will prevent the browser from taking the default action on a specific HTML object.
For example to prevent actoin on a link:
<body>
Click Me
<script>
function dontGo(event) {
event.preventDefault();
}
document.getElementById("clickMe").addEventListener("click",dontGo);
</script>
</body>

Why does my code change the innertext back to the starting value? [duplicate]

I am rather new to Javascript and am currently trying some stuff out with it.
I stumbled upon a tutorial in w3schools on how to change the color of a button after pressing it.
I wanted to do something similar, but instead load another page with some search query results when the button is pressed.
My html code for this is the following:
<html>
<head>
<meta charset = "utf-8">
<title>Test</title>
<script type="text/javascript" src="search.js" defer></script>
</head>
<body>
<header>
<h1>Test</h1>
</header>
<main>
<form>
<input type="search" id="query" placeholder="Search...">
<button id="submit">Search</button>
</form>
</main>
</body>
</html>
And here is the corresponding javascript code:
const searchbutton = document.getElementById("submit");
searchbutton.addEventListener("click", testmethod);
function testmethod() {
window.location.href="search.html";
}
The code itself seems to be working, but whenever the button is pressed, the search.html page loads for a split second before reverting back. I even copied the code from the w3schools tutorial directly but it's still not working.
Any idea what causes the page to get changed back after the button is pressed?
Thanks in advance!
Change location or submitting a form will (re)load the (target) page - you are doing BOTH.
You can start by passing in the event and using event.preventDefault() in the testmethod and then do something else than changing location
I strongly suggest to NOT assign events to a submit button, instead use the submit event
You also need to wrap in a page load event listener or move the script to after the form
ALSO never call anything submit in a form
function testmethod(e) {
e.preventDefault(); // stop submission
console.log(this.query.value);
this.subbut.style.color = "red";
}
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", testmethod);
});
<main>
<form id="myForm">
<input type="search" name="query" id="query" placeholder="Search...">
<button name="subbut">Search</button>
</form>
</main>
If you do not need to submit the form, use a type="button" and no form
function testmethod(e) {
console.log(document.getElementById("query").value)
this.style.color = "red";
}
window.addEventListener("load", function() {
document.getElementById("subbut").addEventListener("click", testmethod);
});
<main>
<input type="search" id="query" placeholder="Search...">
<button type="button" id="subbut">Search</button>
</main>

Unable to get value of form field

I'm learning javascript and tried my hand at calling functions. Based on the example here, I tried to use the logic in my test html:
<html>
<head>
<script>
function ShowForm()
{
var field_value = document.forms["test_form"]["my_name"].value;
document.write(field_value);
}
</script>
</head>
<body>
<form action="" name="test_form" onsubmit="return ShowForm();" method="post">
<input type="text" name="my_name" placeholder="Type your name"/>
<button type="submit">My button</button>
</form>
</body>
</html>
I found that the html renders correctly, however upon clicking the "My button" button, the page simply reloads without displaying the additional html I expected.
The main different is that I'm trying to use <button> for the click/submit action. Is it possible to use a <button> and activate the javascript? Or should I just style the <input> as a button?
What am I doing wrong here?
Use
onsubmit="ShowForm();return false"
Instead of
onsubmit="return ShowForm();"
Adding return false will prevent page from reloading, removing return from return ShowForm(); will allow javascript to run return false after ShowForm().
Example

Why can't I use onsubmit to change innerHTML?

I need to use form fields in an English/Amino Acid Code translater. The code below is simplified to show the problem I'm having. I want to change some text with a javascript function.
If I use an input of type: button with onclick it works.
A submit button with onsubmit in a form changes the text for a split second, then it changes back. I need to use a form for my translation program so how can I make it work?
Extra Credit: Why does it change for a split second with onsubmit?
<html>
<head>
<script type="text/javascript">
function changeTo(text){
document.getElementById("p1").innerHTML=text;
}
</script>
</head>
<body>
<h1 style="text-align:center;">Change text in an element</h1>
<!--
<form onsubmit="changeTo('Hello World');">
<input type="submit" />
</form>
-->
<input type="button" onclick="changeTo('Hello World');" />
<p id="p1">text</p>
</body>
</html>
It's changing it back because the form is submitting. It posts to the same page, and if you are on a local machine it might be so quick you don't notice. Try:
<form onsubmit="changeTo('Hello World');return false;">
<input type="submit" />
</form>
Return false at the end there will stop the submission process.

HTML button to NOT submit form

I have a form. Outside that form, I have a button. A simple button, like this:
<button>My Button</button>
Nevertheless, when I click it, it submits the form. Here's the code:
<form id="myform">
<label>Label
<input />
</label>
</form>
<button>My Button</button>
All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.
<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit
Button state.
return false; at the end of the onclick handler will do the job. However, it's be better to simply add type="button" to the <button> - that way it behaves properly even without any JavaScript.
By default, html buttons submit a form.
This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)
In other words, the button type is "submit" by default
<button type="submit">Button Text</button>
Therefore an easy way to get around this is to use the button type.
<button type="button">Button Text</button>
Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead
To find out more, check out the Mozilla Developer Network's information on buttons: https://developer.mozilla.org/en/docs/Web/HTML/Element/button
Dave Markle is correct. From W3School's website:
Always specify the type attribute for
the button. The default type for
Internet Explorer is "button", while
in other browsers (and in the W3C
specification) it is "submit".
In other words, the browser you're using is following W3C's specification.
Another option that worked for me was to add onsubmit="return false;" to the form tag.
<form onsubmit="return false;">
Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element that won't submit.
It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)
Some reference material
For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.
Late in the game, but you don't need ANY JavaScript code to use a button as a button. The default behavior is to submit the form, most people don't realize that. The type parameter has three options: submit (default), button and reset. The cool thing about this is if you add an event handler it will bypass submitting the form.
<button type="button">My Button</button>
There is also way to prevent doing the submit when clicking the button.
To achieve this, you have to use event.preventDefault() method.
document.querySelector("button#myButton").addEventListener("click", (event) => {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you submit this!<br>";
event.preventDefault();
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<form id="myform">
<label>Label
<input />
</label>
<button id="myButton">My Button</button>
</form>
<div id="output-box"></div>
<script src="src/script.js"></script>
</body>
</html>

Categories