onsubmit not being called on an HTML form - javascript

I have the following form as part of my webpage:
<form id="collabAccess" onsubmit="submitCollabForm()" >
<div id="row-1">
<div class="two-col" id="email"><input type="text" placeholder="Enter email addresses separated by commas"/></div>
<div id="collabSelect" class="collab two-col styled-select">
<select id="collabaccess">
<option>Can Read</option>
<option>Can Write</option>
<option>Can Read & Write </option>
<option>Administrator </option>
</select>
</div>
</div>
<div id="message">
<textarea id="personalMessage" cols="154" rows="10" placeholder="Optional: include a personal message"></textarea>
</div>
<div id="submit-wrapper"><input type="submit" value="Add Collaborators" id="addCollaborators" disabled='disabled' class="small-btn disabled"/></div>
</form>
The function submitCollabForm() is as follows:
function submitCollabForm() {
console.log('in submitCollabForm');
var valid = validateEmails();
if (valid == false) {
var email = document.getElementById('email');
email.addClass('error');
}
}
where validateEmails() is just another js function for validating that the email addresses int he form have the correct format.
However, it looks like onsubmit is not being called at all. Even if I change things to onsubmit="console.log('xyz'), no console statement is being output. I've also checked for javascript errors in the console, but I am getting nothing.
Is there any reason why onsubmit is not working properly?

Your validation function needs to return false to stop the form from submitting. It's better to have
onsubmit="return submitCollabForm()"
See With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"? for details.

The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.

if you feel all code is correct still it's not working then,
Simple steps to do,
1) create one script tag in the same page where your form is, create one function and set one alert and test it. If it is working then try following steps.
2) Try to check the path of your javascript file.
3) if path is correct, then change the name of your javascript function sometimes your name tag conflicts with your function name, and submit points to it, so your call is not reaching at your function. It happened with me. so I posted it here, hope it will be helpful to someone.

Related

HTML required attribute doesn't work with google recaptcha

Require attribute on the input field doesn't work when i implement google recaptcha. When the input is empty, the form is supposed not to be submitted. But the form gets submitted when input is empty. I followed google's guide to implement that in its simplest form.
<?php if (isset($_POST['code']) && ($_POST['code'] == "whatever")) //do stuff?> ?>
What i want to do is to make the recaptcha execute only when the input is not empty, else prevent form submit and recaptcha execution.
<form id="form1" method="post" >
<input name="code" type="text" required>
<button data-sitekey="xxx"
data-callback='onSubmit' type="submit" class="g-recaptcha" >Let me in</button>
</form>
</div>
<script>
function onSubmit(token) {
document.getElementById("form1").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Looking over the documentation you linked to, you are probably better off getting rid of the required attribute and adding a check to your script to not submit the form if the I put field is null.
So JavaScript would be checking if the field is empty and then give a validation alert or however works best for your situation.
The reason it submits is your JavaScript function is calling submit directly, which is bypassing the HTML5-only validation. The submit button being a type of 'submit' will do the submission for you automatically so you don't need it.

Use form data to update web page

Before I provide a bunch of code I'd like to first find out if what I'm trying to do is even possible.
I've created a web based version of the dice game called PIG using HTML & JavaScript. The user can change some of the game's settings by clicking on a "Settings" button on the main page. This button brings up a modal window containing an HTML form (). I'd like to use the data that the users enters and submits on this form to update various settings on the game's main page.
I chose to use an HTML5 form because was hoping to use the native HTML5 form validation capabilities rather than try and replicate that validation checking logic myself using JavaScript.
So my approach was to use javascript to get the data off the form on submit. I tried two different approaches to get this to work:
1) Using an "onsubmit=function getSettings()" on the tag
2) Using a submit button for the form with an onclick="getSettings()".
With both of these approaches I was able to successfully get all the values from the form on submit and use those values to successfully populate the main game page using the gettSettings() function however when I exit the getSettings() function the webpage values that I updated don't stick...they revert back to the original values regardless of which of these two approaches I use.
I know the values were successfully updated because when I set a break point on the last statement of the getSettings() method I can see that all of the values on the main page have been updated to reflect what was filled in on the form...so I know I'm grabbing all of the data successfully and updating the main page with those values.
I'm puzzled as to why the values that I successfully change on the web page simply revert back to their original value upon exit of the getSettings() function.
Maybe it's just not possible to do what I'm trying to do? And if not does anyone know why given I can see the values are successfully changed before they revert back to their original value. What am I missing?
Again I'm using a Form and collecting the data on submit so that I can leverage the "native" HTML5 form validation capabilities.
Regards.
***** EDIT TO ADD KEY SEGMENTS OF CODE *******
Here is the code HTML Code for the modal form:
<form name="config-settings" onsubmit="getSettings()">
<!-- <form name="config-settings">-->
<span class="errMsg"></span>
<div class="row clearfix">
<div>
<label>Player 1:</label>
</div>
<div>
<input type="text" name="input-name-0" id="input-name-0" maxlength="10" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Player 2:</label>
</div>
<div>
<input type="text" name="input-name-1" id="input-name-1" maxlength="6" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Winning Score:</label>
</div>
<div>
<input type="number" name="winning-score" id="winning-score" default="100" placeholder="Enter winning score">
</div>
</div>
<div class="row clearfix">
<div>
<label>Number of Dice:</label>
</div>
<div>
<select name="diceValues" id="dice-value">
<option value=""> - Select - </option>
<option value="dice-1">One Dice</option>
<option value="dice-2">Two Dice</option>
</select>
</div>
</div>
<!-- Below is alt method I used to submit form..yields same results -->
<!-- <input type="submit" value="Submit" onclick="getSettings()">-->
<input type="submit" value="Submit">
</form>
Here are the global variables defined and used in getSettings() method:
// Global variables
var scores, roundScore, activePlayer, gamePlaying, gamesWonCount, playerNames, winningScore, numOfDice, matchScore, msgs;
var player0, player1, score;
var player0Field = document.getElementById('name-0');
var player1Field = document.getElementById('name-1');
var scoreField = document.getElementById('winScore');
Here is the listener for the Settings button on the main web page that brings up the setting modal window containing the settings form:
//*********************************************************
// Open Settings Modal Windows
//*********************************************************
document.querySelector('.btn-settings').addEventListener('click', function () {
// Settings can't be changed if game is actively underway
if (!gamePlaying || roundScore === 0) {
document.querySelector('#modal-settings').style.display = 'block';
} else {
// Make error message visible
msgs.style = 'block';
// Create message to indicate settings successfully updated
msgs.textContent = "Settings can't be updated during game";
msgs.style.backgroundColor = 'pink';
fadeOut(msgs);
}
});
Here is the getSettings() javaScript function (note: there are no local variables defined in this function...they are all defined as global values (first few lines of javaScript app).
function getSettings() {
// Alternative call if I want this function to be called via eventListner
//document.querySelector('.btn-save').addEventListener('click', function () {
console.log("getSettings method called");
player0 = document.forms["config-settings"]["input-name-0"].value;
player1 = document.forms["config-settings"]["input-name-1"].value;
score = document.forms["config-settings"]["winning-score"].value;
// Reset msgs so they will be displayed each time
msgs.style = 'block';
playerNames[0] = player0;
player0Field.innerHTML = playerNames[0];
playerNames[1] = player1;
player1Field.textContent = playerNames[1];
// Set Winning score on UI to value on form
scoreField.textContent = score;
// numOfDice = document.getElementById('dice-value').value;
// Create message to indicate settings successfully updated
msgs.textContent = "Successfully updated settings";
msgs.style.backgroundColor = 'lightgreen';
fadeOut(msgs);
document.querySelector('#modal-settings').style.display = 'none';
}
I don't know exactly what this getSettings() function of yours is supposed to do, but I can try to give you a piece of advice:
Some of the form validation capabilities of HTML5 are not entirely supported on all of the used browsers(some users don't fancy to update their browser). Therefore relying on the "native" validation of HTML5 isn't exactly best practice.
If you want to manipulate the form values in any way before submitting the form I would rather add a listener to the submit button for click events, prevent any other action, make the checks/ manipulation of the form data and then manually submit the form. Anyways, front-end validation isn't entirely safe, so if you're peddling sensitive data it's mandatory that you'll make checks on serverside(if your app uses a server).
To exemplify what I've explained earlier:
document.getElementById("myBtn").addEventListener("click", function(event){
//Stops the form submitting.
event.stopImmediatePropagation();
//Do the checks here.
//Sends the form.
document.getelementById("myForm").sumbit();
);
If you change local variables inside this getSettings() function, the variables will be changed only within the function scope. You might want to read about scope in javascript. (this was just an educated guess).
I hope you find this useful, good luck!
Okay...I finally figured it out! The problem was not a scoping problem but instead and issue with how "onSubmit" works.
The solution involved making two changes:
1) Adding a return statement to the "onsubmit" attribute when calling the "getSettings()" function;
<form name="config-settings" onsubmit="return getSettings()">
2) Returning false at the end of the gettSettings();
return false;
Note: I had previously tried returning true but not false. I was errantly under the impression that returning false value from getSettings() function would disable HTML5 "native" validation and force me to implement all of the error checking myself...which was not what I wanted. It is now my understanding that returning false merely prevents the form from being submitted..but it doesn't disable the HTML5 native validations.
This solution worked perfectly for me because my goal was not to submit the form to the server (as there is no server component here) but merely to use the "native" HTML5 form checking and then update the values on the local web page.
With all of that said I'm still not entirely sure why when I didn't provide the return statement or when I returned true why all of my changes reverted back to their originally value. If anyone can shed some light on why I'd appreciate it.
Cheers

Javascript fail to execute function - onsubmit and action

I am creating a page that is only javascript and html. I have 2 problems.
When it calls the function inputs() in this form, it fails at the first time and success on the next submissions.
<div id="container">
<form onsubmit="inputs()" action="#">
Variables: <input type="number" id="vars" size="1" required/>
Constraints: <input type="number" id="cons" size="1" required/>
<input type="submit" value="Submit">
</form>
</div>
I wasnt able to solve this but I skipped it because it still proceeds to the inputs() the next submissions.
But in my inputs(), i created a form dynamically. The form is created as this:
var form = document.createElement("form");
form.setAttribute("action","#");
form.setAttribute("onsubmit","solve()");
Now, when I submit the dynamically created form, the problem is it goes back to the first set of form. solve() was not called.
Why is it? What should be edited?
Thanks for the help in advance.
solve() has these lines of codes. It's just a test if it will successfully go into it but it fails. This just deletes all the elements.
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
This line
form.setAttribute("onsubmit","solve()");
isn't doing what you think it does. If it was in the actual html it would work but not now. What it does is just make the attribute appear in the console. The event handler isn't actually being set.
Instead do it via onsubmit property or addEventListener
form.onsubmit = solve; // now it must work
Try return false at the end of the function solve. this should work to show but would not perform action. Also add "return solve()" instead of "solve()".

jQuery form submit doesn't appear to trigger if statement

I have this error but I can't see how to fix it. I've used JSLint with some results (it just tells me document isn't a global value, or the 'else clause' was not needed, etc) but no solution.
I have a form to be submitted and I need to compare that both email fields are equal. So I want a nice simple email1 == email2 script, jQuery isn't my strongest point, but I came up with this:
My form ID is "regIn", my email fields are type="email" (HTML5) and id="MailA" and id="MailB" respectively.
I have preloaded jquery 1.11.1.min.js
My jQuery code (see below why the #forgotten is still in there):
$(document).ready(function() {
$('#forgotten').click(function() {
$('#passbox').toggle(360);
return false;
});
$('#regIn').submit(function() {
// * referenced; but this isn't in the code: alert('alert1');
if ($('#MailA').val() === $('#MailB').val()) {
return true;
}
$('#errorMsg').innerHTML("Emails need to be the same!");
alert('Hello');
return false;
});
});
So - I use Alerts to see how far the script gets (i know, tacky debugging). firebug doesn't report page errors or script errors that I can see. The "alert 1" always fires on form submission, and successfully shows me the values of #MailA.val() and #MailB.val(),
But the if statement doesn't seem to fire at all. I have tried making the values variables (var d1 = $('#MailA').val() etc. ) but that doesn't change anything, the form always submits and neither the if or the else (which did surround the text below the if statement clause but JSLint said it wasn't needed so I removed it).
I have also used variations of syntax, using != and == but was also reading from JSLint that === and !== are preferred.
My HTML:
<form enctype="multipart/form-data" name="regIn" id="regIn" autocomplete="off" accept-charset="utf-8" action="#" method="post">
<div class="inputContainer">
<input type="email" value="" tabindex="31" id="MailA" name="regMailA" required>
</div>
<div id="errorMsg"></div>
<div class="inputContainer">
<input type="email" value="" id="MailB" tabindex="32" name="regMailB" required>
</div>
<div class="registerRow">
<input type="submit" class="regButton" value="Register" tabindex="34">
</div>
</form>
As I said, I've looked around for the last hour or so and I just can't see what it is.
Obviously the code is stripped down for the question, the only other aspect is that there is another piece of jQuery in the document ready function - as shown the #forgotten appears for showing / hiding an info. box, this works fine.
please note that you are using:
$('#errorMsg').innerHTML("Emails need to be the same!");
if you try to alert $('#errorMsg').innerHTML it will be undefined.
When you using JQuery selectors $('#errorMsg') JQuery will wrap the dom object with JQuery dom object that own JQuery special methods(val, html, etc), so you don't have access to the core method innerHTML, instead you should use:
$('#errorMsg').html("Emails need to be the same!");
Enjoy!

How can I submit a form automatically (onevent) with javascript?

I'd like to be able to submit a form automatically on an event ( a generic form, for user tracking).
For example, create a POST to
http://www.example.com/index.php?option=track&variable=variable
application/x-www-form-urlencoded with stuff like
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2
The actual string will be preformatted, though, because all it is is like a 'ping'.
It needs to be submitted onevent, with external js ( http://example.com/scripts/js.js )
What the hay should I do? This is getting annoying.
Update: I guess I didn't really make myself clear; I have a premade form that isn't supposed to display on the page; it needs to submit on an event. The form fields do not exist on the page; all I do is link to the script on the page and it executes onLoad.
POST uri: http://www.example.com/index.php?option=track&variable=variable
The arguments above (option=track and variable=variable) are not the form details (postdata).
The content type is application/x-www-form-urlencoded , and has the following keys/values.
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2 (when encoded, the spaces get turned to %20's.)
I need a script that submits this when run.
You have to get the form object and call the submit(); function provided by HTMLFormObject.
document.getElementById('myForm').submit();
1) with the following, (while page is loaded), the form will be immediately autosubmited
<form action="post.php" name="FNAME" method="post">
<input type="text" name="example22" value="YOURVALUE" />
<input type="submit" />
</form>
<SCRIPT TYPE="text/JavaScript">document.forms["FNAME"].submit();</SCRIPT>
another formSubmit alternative - submits any script:
document.forms[0].submit();
2) or use button click after 2second:
<SCRIPT TYPE="text/JavaScript">setInterval(function () {document.getElementById("myButtonId").click();}, 2000);</SCRIPT>

Categories

Resources