Using addEventListener onSubmit form - javascript

I am quite new to HTML and JavaScript. Below is the sample code. The below code block works fine with onsubmit as form tag attribute
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#" onsubmit="functSubmit()">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
<script>
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
</script>
</body>
</html>
But when I write below code with addEventListener() it does not work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
<script>
document.getElementById("form1").addEventListener('submit', functSubmit(event));
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
</script>
</body>
</html>
Why might addEventListener not be working?

That's because you're immediately invoking the event listener's callback. Just pass the function as an argument, without invoking it. Anytime the form is submitted, that function will have the event object passed into it.
document.getElementById("form1").addEventListener('submit', functSubmit);
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
</body>
</html>
On a side note: it's generally better practice to separate the concern of your HTML from your JavaScript. While inlining your event handlers in attributes works, it couples two separate concerns. For maintainability's sake, manage your handlers separately. You also get the benefit of leveraging event delegation.

You are invoking functSubmit and passing the result to the addEventListner function.
Instead you want something like this
<form id="form1" action="#" onsubmit="functSubmit()">
or
document.getElementById("form1").addEventListener('submit',functSubmit);
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
event is already passed in by the caller of the functSubmit function.

I think you can only pass a string as function name. You can try
document.getElementById("form1").addEventListener('submit', function(event){
functSubmit(event);
});

Related

HTML Form onsubmit

In HTML5, returning false in a form gives the red line, indicating there is an error, even though I am able to achieve my expected output. Is there any way to fix this line and have a bug free code as it is triggering my OCD.
Also, I am a big beginner with my code so please try to keep it as simple as possible. i do not understand JQUERY at all.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title of the document</title>
</head>
<body>
<form action="#" method="get" onsubmit="userRegister1(event)">
<input type="text" name="name" />
<button type="submit">Click me</button>
</form>
</body>
</html>
<script>
function userRegister1(event) {
event.preventDefault();
return false;
}
</script>
<form action="#" method="get">
<input type="text" name="name">
<button type="submit" onclick="
// you can code javascript code here, this's same how you code in <script>.....</script>
function userRegister1(){
console.log('your code in userRegister1 function');
}
userRegister1();
// so you return false that's wrong syntax
//onsubmit='userRegister1(); return false;'
// return must be use in function, in this case you can use in function userRegister1()
// BUT i don't suggest use this way
">Click me</button>
</form>

ReferenceError: Can't find variable X when calling JS function (or variable) from HTML file

I am trying to call a function in an external JavaScript file from an HTML-file. The goal is to work with the content of a form there.
I tried so many things and always got the Error "ReferenceError: Can't find variable: X"
The positioning of the jquery javascript file loading
The positioning of the <script src="XXX"> call
Calling the function from the button "onclick" or the form "onsubmit"
Trying to call the javascript file from an embedded script in the HTML
This is what my JavaScript file and my HTML looks like right now:
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
</body>
I also tried
function doSomething() {
// Do something
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
<script>
function submit(e) {
doSomething();
}
</script>
</body>
In both cases, it returned the same error over and over again: "ReferenceError: Can't find variable: X". In the first example, X being "submit" and in the second "doSomething".
All help is very welcome. I know there are similar headlines here, but non of the solutions did anything for me.
Hey so when I ran the code without the e as a parameter for the submit function in the html it didn't give me the error. I think it may be because the e is the place holder for the text of the submit function in this case. Hope this helps.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit()">Send</button>
</form>
<script type="text/javascript">
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
</script>
</body>
</html>

Javascript, how to check if handler is attached

If I run dispatchEvent, on an element that has no handlers attached, nothing happens.
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
var event = new Event('submit');
var result = target.dispatchEvent(event);
// nothing happens because no handler is attached to target submit event
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
How can I determine that no handler is attached an then decide to manually run the document.getElementById('myForm').submit(); ?
I need a Vanilla Js answer...
In pseudo Javascript it would be something like:
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
if(target.hasEventListener('submit')) {
var event = new Event('submit');
var result = target.dispatchEvent(event);
}
else {
target.submit();
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
Update
I think that this is a Chrome issue, Firefox behavior is different: when you call dispatchEvent if no custom handler is defined, it fires the native "html" submit event (the same as document.getElementById('myForm').submit())

Why does getting my form with document.getElementByID stop alert() from firing?

I'm trying to alert the values of the form elements but this isn't functioning even at its simplest: getting the elements of the form then alerting a string.
The alert fires when it's by itself, but not when I put the form's data in the variable. Why?
I'm sure there's probably a very simple mistake in here somewhere, but I'm stumped.
<!DOCTYPE html>
<html>
<head>
<!-- ISTE240 Exercise 5b -->
<meta charset=utf-8 />
<title>Get elements from a form</title>
<script>
function getFormValues() {
// function to send first and last names to an 'alert' message.
alert("test");
var form = document.getElementById(“regForm”).elements;
}
</script>
</head>
<body>
<p>JavaScript Exercise 5b </p>
<form id="regForm" onsubmit="getFormValues()">
First name: <input type="text" name="fname" value="Boo"><br>
Last name: <input type="text" name="lname" value="Radley"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
By default form tag will try to submit form values. You must prevent default behavior, demo below
document.querySelector('#regForm').onsubmit = function(e){
e.preventDefault();
alert('a');
var form = document.getElementById("regForm").elements; //<-- wrong syntax, must be "
console.log(form);
}
<!DOCTYPE html>
<html>
<head>
<!-- ISTE240 Exercise 5b -->
<meta charset=utf-8 />
<title>Get elements from a form</title>
</head>
<body>
<p>JavaScript Exercise 5b</p>
<form id="regForm">
First name:
<input type="text" name="fname" value="Boo">
<br>Last name:
<input type="text" name="lname" value="Radley">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

passing variable to javascript function and using it in document.form?

<!DOCTYPE html>
<html>
<head>
<title>Database test</title>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
function validateForm(n)
{
var x=document.forms.SignUp.n.value;
alert("*"+x+"*");
}
</script>
</head>
<body>
<h1>Just a Database test</h1>
<form name="SignUp" action="http://127.0.0.1/cgi-bin/connectivity.cgi" onsubmit="return validateForm();" method="post">
Ename :<input type="text" name="ename" onchange="validateForm('ename');"><br><p id="error_1"></p>
<input type="submit" value="Send">
</form>
</body>
</html>
I am trying to pass the user input value by onchange="validateForm('ename') but it does not seem to work i dont get anything.
instead if i change function to this then it works but again i need to pass it as varaible from onchange="validateForm('ename').
function validateForm(n)
{
alert("*"+n+"*");
}
You should pass the element itself, which is this inside an inline handler:
validateForm(this);
function validateForm(elem)
alert(elem.value);
}
One way to make it work, without changing your function call:
function validateForm(n) {
var x = document.forms.SignUp[n].value;
alert("*"+x+"*");
}

Categories