form javascript submit event - javascript

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>

Related

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.

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

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.

How to grab the onSubmit event for a form?

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;
}

Categories