How to grab the onSubmit event for a form? - javascript

I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)
I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.
Here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Test</h2>
<form action="#" method="post" id="commentform">
<p><input type="text" name="author" id="author" size="22" tabindex="1" />
<label for="author"><small>Name (required)</small></label></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
</form>
<script type="text/JavaScript">
<!--
alert("Hello world");
var formCheck = document.getElementById("commentform");
formCheck.onSubmit = doMapping();
function doMapping() {
alert("form submitted");
return false;
}
-->
</script>
</body>
</html>

Change this:
formCheck.onSubmit = doMapping()
to this:
formCheck.onSubmit = doMapping
When you add parenthesis to the end of a function you execute that function. When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.
Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):
function doMapping() {
alert("form submitted");
return false;
}
formCheck.onSubmit = doMapping();
However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:
formCheck.onSubmit = function() {
alert("form submitted");
return false;
}
which seems a bit cleaner to me.

Using jQuery.
$(document).ready( function() {
$('#commentform').submit( function() {
alert('form submitted');
return false;
});
});

Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.
window.onload = function(){
if (document.getElementById("commentform")){
document.getElementById("commentform").onsubmit = doMapping;
}
}
function doMapping(){
alert("form submitted");
return false;
}

Related

How to close popup window after clicking on submit button without page reload?

I have a Script to open one popup with form(for comparing the input field value with one fixed code) on page load & after clicking on the submit button need to close popup without page reload. Here is my code.
"Html form code"
<form method="post" onsubmit="return checkCode(this);">
<div class="form-group">
<input type="text" required class="form-control" placeholder="Name" name="name">
</div>
<input type="submit" name="save" class="btn btn-primary">
</form>
"Script Code"
"popup script"
<script type='text/javascript'>
$(function () {
var overlay = $('<div id="overlay"></div>');
overlay.show();
overlay.appendTo(document.body);
$('.popup').show();
$('.close').click(function () {
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
});
});
</script>
"comparing function code"
<script type="text/javascript" language="JavaScript">
function checkCode(theForm) {
if (theForm.name.value != 'SS-2018') {
alert('Code not matched!');
return false;
} else {
return true;
}
}
</script>
Please check this & help me to get it working correctly. Everything is working correctly I just want on click submit page don't reload simply close the popup window & keep on the same page.
Thanks & Regards
Cue
I'm assuming the HTML that you have there is inside of your popup or overlay. It's a bit hard to tell.
If you want to submit the form without reloading or changing the page, you'll have to use some form of AJAX. Since it looks like you are using jQuery, you can use their ajax() function.
To get the data of the form itself, you can use their serialize() function to scoop the data up into a POJO (plain old JavaScript object).
You would do this on whatever makes sense to call submit. You could probably do it instead of your return true in your checkCode() function (and always return false).
It'd be something like this:
<script type="text/javascript" language="JavaScript">
function checkCode(theForm) {
if (theForm.name.value != 'SS-2018') {
alert('Code not matched!');
} else {
$.ajax('http://example.com/post/location', { method: 'post', data: $(theForm).serialize() })
.then(response => { /* do something with response */ })
.catch(err => { /* handle error */ });
}
return false;
}
</script>

Javascript function does not wait for the callback function to complete

I have an online platform for which I want every HTML form submitted by users to be digitally signed using Digital Signature Token.
I am testing an API(Javscript API + .exe (that need to be installed at the users' machine)).
The code goes like this
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sign Form Page</title>
<script type="text/javascript" src="docsign.js"></script>
</head>
<body>
<script type="text/javascript">
var DocSignObj = _docSignObj;
var myCallbackFun;
$(function(){
//This lets the API know that SignData() function needs to call
//myCallbackFun function after its job is done
DocSignObj._initialize(myCallbackFun);
});
function sign(form){
//does some stuff like serializing form data etc
var formData =serialize(form);
//This function is exposed by the API.
//It opens the dialog box to get Digital Certificate Details from
//user,
//validates the details and
//then generates the Digital Signature which is returned in the
//callback
//function
DocSignObj.SignData(formData);
}
function submitForm(){
//Once this function is called it should wait till myCallbackFun does
//its job.
sign(form);
//The following line of code is executed immediately instead leaving
//DIG_SIG element as empty
document.FORM_TO_BE_SIGNED.submit();
}
function myCallbackFun(result){
var digitalSignature = result.sig;
document.getElementById("DIG_SIG").value = digitalSignature;
}
</script>
<form id="FORM_TO_BE_SIGNED" action="" method="">
<input type="hidden" id ="DIG_SIG" value="" />
<input type="text" id="data" /></br>
<input type="submit"
value="Sign Form Data" onclick="submitForm()" />
</form>
</body>
</html>
What happens is that the
document.FORM_TO_BE_SIGNED.submit();
line executes immediately after the
sign(form);
and the form gets submitted without signing.
You have lots of errors among passing some undefined form to sign( form ), serializing a form without using name="" for your inputs etc...
Instead of counting your errors, here's how I'd do it... hopefully you'll find all the comments in the below example clear enough, but for further question feel free to ask so I can improve:
// Let's say it does this...
var DocSignObj = {
data: {
sig: "sig_012345679abcd_sig" // Some digital signature
},
SignData: function(serializedForm) {
this.data.serializedForm = serializedForm;
return this.data;
},
_initialize: function(cb) {
return cb(this.data);
}
};
// Now...
function myCallbackFun(result) {
// DIGITALLY SIGN BY API CALLBACK
$("#DIG_SIG").val(result.sig);
}
function sign(form) {
// does some stuff like serializing form data etc
DocSignObj.SignData($(form).serialize());
// presumably it checks if the "sig_***_sig"
// from the serialized string is valid at submit-time.
}
function submitForm(event) {
// 1 DON'T SUBMIT YET
event.preventDefault();
// 2 SIGN IT
var signedData = sign(this); // where `this` is the $form
// 3 SUBMIT FORM
// $(this).submit(); // TODO: uncomment this line to submit form!
console.log("SUBMITTED!!! %o", DocSignObj.data);
}
jQuery(function($) {
//This lets the API know that SignData() function needs to call
//myCallbackFun function after its job is done
DocSignObj._initialize(myCallbackFun);
$("#FORM_TO_BE_SIGNED").on("submit", submitForm);
});
<form id="FORM_TO_BE_SIGNED" action="" method="">
<input name="sign" type="text" id="DIG_SIG" disabled> (the hidden one... just to test if SIG is being added)<br>
<input name="data" type="text" id="data" value="Name Surname"><br>
<input type="submit" value="Sign Form Data">
</form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

HTML Form to display output by using a button

Please let me know what I am doing wrong, I have tried to debug but it hasn't been working. I want to enter information into a text field and then display that after clicking a button.
<!DOCTYPE html>
<html>
<head>
<script type = 'text/javascript'>
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").onclick = display();
</script>
</head>
<body>
<form id='form'method = 'post'>
<p> Name: <input type="text" id="name"/></p>
<p><input id ="Submit" type = "button" value = 'Submit' /></p>
</form>
</body>
</html>
The problem is that you are making use of a <form> POST. The default behaviour is to navigate away from the page (or refresh if you're posting to the same page), and doing so would mean that the script cannot execute any further functionality. To prevent this, you need to use .preventDefault() to prevent the default behaviour of the form submission.
In order to do this, I've changed your .onclick = display() functionality to add an event listener on the click, which prevents the default behaviour, and then calls display():
.addEventListener("click", function(event) {
event.preventDefault();
display();
});
Adding this provides the following working example:
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").addEventListener("click", function(event) {
event.preventDefault();
display();
});
<form id='form' method='post'>
<p> Name: <input type="text" id="name" /></p>
<p><input id="Submit" type="button" value='Submit' /></p>
</form>
Hope this helps! :)
Create an empty p tag and give it an id, then call the id and .html to input the text into the field. Like so
so get your html ready
<p><span id="youridhere"><p>
then add this to your function instead of using alert.
$('#youridhere').html(name);
that should do it
here's a jsfiddle of what I think you are looking for
https://jsfiddle.net/uzdt715L/
$('button').click(function(){
var thing = $('#whatever').val();
$('#final').html(thing);
});
You need to update your click handler syntax. The following should work for you,
document.getElementById("Submit").addEventListener("click", display);
See this related question - addEventListener vs onclick
Your code is not really wrong.
But because the JavaScript is placed before htm code, so the onlick event is not registered.
You must replace
document.getElementById("Submit").onclick = display();
With
document.onload = function() {
document.getElementById("Submit").onclick = display();
}
Sorry for the formatting as I'm answering via mobile.

Why won't the form value show up?

I am creating a simple form, and I want to write to the console the value of the input once the form has been submitted and successfully validated. However, when I go to test my current progress, I input a random piece of text and nothing shows up, even in the console. Here is the code I have now (excluding any commented out code):
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script language="Javascript">
window.onload = function() { // So the DOM can be defined
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>
Even when I type nothing and submit the form, the alert doesn't pop up. There was other posts related to form problems, but they don't have any relation to mine. Is there something wrong with my code? What is the problem and how can I fix it?
Edit: I realized window.onload only executes the code inside of it when the window is loading. After that, all functions cease to exist. In addition to removing the onload handler, I had to relocate the validation function within the body.
Your validateForm function is only visible within your onload function. Additionally, you were comparing the form to an empty string, not the value within the text field in the form. The console.log would also not have been visible, because the page refreshes before you can see it.
Below is the code with those three things fixed.
<html>
<head>
<meta charset="utf-8" />
<script>
function validateForm() {
var text = document.forms['encrypt']['text'].value;
if(text == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
alert("Entered '" + text + "', refreshing now.");
return true;
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>
There's no reason to wrap this function in an onload event handler. And doing so is limiting the scope of the function definition so that the code which tries to call it can't actually see it. (That is, after onload completes, the function you defined is no longer in scope and ceases to exist.)
Just remove the handler and define the function directly:
<script language="Javascript">
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
</script>
The problem is your function validateForm() is not accessible in the scope when you click the submit. You can verify this by call this function in the console.
In your code, it's defined inside the window.onload, so please move the function out of it.
Try to remove window.onload = function() { and just keep the validateForm function.

form javascript submit event

I want to manage a form only with javascript, but the eventlistener doesn't worked for me. What's wrong?
My form:
<script src="init.js"></script>
<div id="search_box">
<form id="search_form">
<input type="search" name="search" autofocus placeholder="Google search" id="searchbox">
<input type="button" value=● id="searchsign">
</form>
</div>
<script src="search.js"></script>
In init.js file:
"use strict";
function $(selector){
return document.querySelector(selector);
}
function $$(selector){
return document.querySelectorAll(selector);
}
in search.js file:
$('#searchsign').addEventListener('click', search);
$('#search_form').addEventListener('submit', search);
function search(){
console.info('search function OK');
var searchvalue = $("#searchbox").value;
var google = "https://www.google.hu/search?site=&source=hp&q=";
window.location = google + searchvalue;
}
The form's submit event will go to the form's action (no action = the current URL) and reload the page.
If you're handling it with JavaScript, accept the event argument and call preventDefault on it to prevent the default behavior:
function search(e) {
e.preventDefault();
// ...
}
I would also suggest either not making your functions globals, or giving search a different name to avoid conflicts in the global namespace.
Side note: You need to URI-encode query string arguments, so change your location assignment to use encodeURIComponent:
window.location = google + encodeURIComponent(searchvalue);
Working copy on JSBin (Since Stack Snippets work in frames that don't allow us to move off to Google)
Source of working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="search_box">
<form id="search_form">
<input type="search" name="search" autofocus placeholder="Google search" id="searchbox">
<input type="button" value=● id="searchsign">
</form>
</div>
<script>
"use strict";
(function() { // Scoping function to avoid globals
function $(selector) {
return document.querySelector(selector);
}
function $$(selector) {
return document.querySelectorAll(selector);
}
$('#searchsign').addEventListener('click', search);
$('#search_form').addEventListener('submit', search);
function search(e) {
e.preventDefault();
console.info('search function OK');
var searchvalue = $("#searchbox").value;
var google = "https://www.google.hu/search?site=&source=hp&q=";
window.location = google + encodeURIComponent(searchvalue);
}
})();
</script>
</body>
</html>
Code looks fine to me here
The results aren't going to show because google does not allow itself to be iframed, but you can see your console logs are printing just fine.
If you are not seeing the same results as above in your code, then I'm guessing there is an issue with the order or manner in which you are including your files.
.
If you want to trigger submit event, do not add click event listener to submit button, instead change its type to submit.
Do not forget to add e.preventDefault() in submit function to prevent default submit behaviour and page reloading
"use strict";
function $(selector) {
return document.querySelector(selector);
}
function $$(selector) {
return document.querySelectorAll(selector);
}
$('#search_form').addEventListener('submit', search);
function search(e) {
e.preventDefault();
console.info('search function OK');
var searchvalue = $("#searchbox").value;
var google = "https://www.google.hu/search?site=&source=hp&q=";
window.location = google + searchvalue;
}
<script src="init.js"></script>
<div id="search_box">
<form id="search_form">
<input type="search" name="search" autofocus placeholder="Google search" id="searchbox">
<input type="submit" value=● id="searchsign">
</form>
</div>
<script src="search.js"></script>

Categories