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
Related
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>
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();
}
I am currently learning JavaScript for my uni course and my function is not being called for some reason. I want to understand why this is not working.
Brief Description
There are two forms, one has a submit button, with the onSubmit field calling document.write() (This works), then calling my own function submit(). If I change submit() to document.write() then I receive two outputs, so there should be no reads why submit is not called?
The second form has a single textbox in it, I ideally want to make this disappear when the button is pressed, however I mainly want to understand why submit is not called.
<html charset="utf-8">
<head>
<title>Game</title>
</head>
<body>
<form method="get" name="form1" action="game.php" onSubmit="document.write('Hello');submit();">
<input type="submit" value="submit" name="button" />
</form>
<form id="form2" name="form2">
<input name="letter" type="text" />
</form>
<script>
function submit() {
alert("HELLO");
document.getElementById('form2').visibility='hidden';
document.write("Hello");
}
</script>
</body>
I have tried inserting the script in the header, above the function, below the function, but nothing seems to work.
Hope someone can help, thanks
submit is a reserved keyword. Change to any other name and it should work. Please find the JSFiddle of the same
https://jsfiddle.net/pc9rL2ey/
function submita() {
alert("HELLO");
document.getElementById('form2').visibility='hidden';
document.write("Hello");
}
<form method="get" name="form1" action="game.php" onSubmit="submita();document.write('Hello');">
I have a simple form which has nothing other than a submit button. All I want to do is prevent submission of the form (I know it doesn't make any sense but this is only for illustration). So I'm making use of the form's onsubmit event and this event returns false. This does work but this is where the 'incomprehensible behavior' arises.
I can associate the return false; statement with the onsubmit event of the form either by using inline JavaScript or keep it in a different place.
<form onsubmit="return false;" id="form1" method="post">
<input type="submit" id="btnButton" value="Submit" />
</form>
Now, the aforementioned code works just fine. See => http://jsfiddle.net/MccK5/
I can even modify the above code as follows in order to make the JavaScript separate (unobtrusive).
--some html markup initially
<form onsubmit="return falsifier()" id="form1" method="post">
<input type="submit" id="btnButton" value="Submit" />
</form>
<script>
function falsifier() {
return false;
}
</script>
--other html markup follows
Here, the script tag is placed right after form in the HTML markup.
This works too. See => http://jsfiddle.net/AfdQ5/
But when I shift the JavaScript to an different place (ex: external file), this doesn't seem to work.
By taking a look into the console in inspect element, I noted the error falsifier is not defined.
See this here => http://jsfiddle.net/5cR5R/2/
Could someone elaborate on why this is so?
You're encountering a design feature (or flaw) in JSFiddle:
In JSFiddle, the "JavaScript" pane is not the direct source code of a referenced JavaScript file, instead JSFiddle wraps that code as below and inserts it into <head>. Just go View Source to see what it does:
<script type='text/javascript'>
//<![CDATA[
window.onload=function(){
function falsifier() {
return false;
}
}
//]]>
</script>
Your <form> elements can't find falsifier because falsifier only exists within the scope of this anonymous function.
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.