HTML required attribute doesn't work with google recaptcha - javascript

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.

Related

onsubmit not being called on an HTML form

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.

Javascript Auto Form submission not working

I have following simple HTML Form & i tried to submit the form automatically during page load.
Below Javascript code is not automatically submitting the form.
HTML :
<form action="SSL.php" method="POST" name="TForm" id="transactionForm">
<input type="hidden" name="merchantTxnId" id="merchantTxnId" value="test">
<input type="submit" name="submit" id="submit" value="submit" style="visibility:hidden">
</form>
Redirecting ... Please wait...
Java script:
<script>
window.onload = function(){
alert(1); // this is working..
document.getElementById("transactionForm").submit(); //nothing is happening with this line . form is not getting submitted
}
</script>
I found following error in Chrome console mode says:
Kindly suggest me where the problem is...
You may not use submit as the name or id of any of your form elements.
The reason is, that you can reach each child of your form via document.getElementById('form').nameOfTheChild where nameOfTheChild is the name of the child. If you have a child with the name submit, document.getElementById('form').submit is a shortcut to address that child.
The documentation of .submit() says that :
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures.

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>

How to change the value of textbox when form is submitted?

I have a form which has fields pre-filled with a default value, like this:
<input type=text name=first value="First Name" class="unfilled" />
When the textbox is clicked, the class unfilled is removed from the textbox, and the textbox is made blank so the user can type in his/her own info.
The problem is that when the form is submitted, its getting submitted with these default values, which is messing up the server side validation. How can I do it so that when the form is submitted, all the fields which have a default value are made blank, so the server side validation would throw the error: 'Please fill in this field'?
I'm trying the following code which isn't working:
$("#myForm").submit(function()
{
$(".unfilled").val('');
}
);
This does make the fields blank, but the server still receives them with their previous default values.
I think you simply have a syntax error. You're missing the closing parenthesis on your submit method.
I just whipped this up and it works fine
<!DOCTYPE html>
<html>
<body>
<?php
var_dump($_POST);
?>
<form action="test.php" method="post">
<input type="text" name="first" value="First Name" class="unfilled">
<input type="submit">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('form').submit(function() {
$('.unfilled').val('');
});
});
</script>
</body>
</html>
You need to stop the form execution first, change the values, and then manually submit the form.
$("#myForm").submit(function(e)
{
// Stop the form submit
e.preventDefault();
$(".unfilled").val('');
$(this).submit();
}
You have to return true; if you want the form to submit, or false, if you don't.
The problem with this approach is that the fields will 'blink' before posting the values, thus creating a bit of unprofessional feel.
It is better to use hidden values and set them in submit() event.
I think you need the .click() function of JQuery.
Example:
$(function () { // shorthand for document.ready
$('.unfilled').click(function () {
$(this)
.val('')
.removeClass('unfilled');
})
});
UPDATE
Sorry, i missunderstand you, thought you need a feature like a placeholder.
Of couse you can do it with return false;, but this cancel the submitting. Or like GreenWebDev says to use e.preventDefault();.

Hitting enter in any textbox in chrome triggers the form submit, even when there is no submit button

I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
use this syntax:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13
Try this method:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not.
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.
So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)

Categories

Resources