I have got more than 4 google recaptcha on the same page. I managed to get them showing, but validating is not working.
$('#newsletter').on('submit', function(e) {
var response = grecaptcha.getResponse();
if (response.length == 0) {
e.preventDefault();
alert("Incorrect captcha code. Please try again.");
return false;
} else {
return true;
}
});
<form action="" method="post" id="newsletter">
<div id="sideRecaptcha" class="g-recaptcha"></div>
<input type="submit" value="submit" />
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit&hl=en" async defer></script>
<script>
var reCaptchaCallback = function() {
var elements = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].getAttribute('id');
var widgetId = grecaptcha.render(id, {
'sitekey' : 'XXXXXXXX',
theme' : 'light'
});
elements[i].setAttribute('cid', widgetId);
grecaptcha.reset(widgetId);
}
};
</script>
grecaptcha.getResponse() always return empty. Any idea?
Related
I want the form data that was submitted on page load via POST method
Here is my code
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>
What I want is to get the form data when ever this page is loaded
What I tried
document.getElementsByTagName('form')[0].onsubmit = function () {
var status, date;var str = '';
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
else if (date != null) {
str += date.value;
}
}//func close
Why are you submitting the form while user has not even filled the form body onload !
If you are allowed to use Jquery it will do your task easy
document.getElementsByTagName('form')[0].onsubmit = function () {
$(this).serializeArray();
}//func close
Please have a look at this link for details
Here is a small demonstration
$(document).ready(
function() {
$("#Form1").on('submit', function() {
var data = $(this).serializeArray()
console.log(data);
for (var i = 0; i < data.length; i++) {
document.body.innerHTML += 'Key: '+data[i].name +' and Value: '+ data[i].value + '</br>';
}
return false;
});
$("#Form1").submit();
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
You need to write your code inside window.onload evnet.
Try this
window.onload = function() {
var str = '';
var status, date;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
if (date != null) {
str += date.value;
}
alert(str);
};
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>
$(document).ready(function() {
$("#submit").click(function() {
var value = document.getElementById("txt_sketch_no").value;
var process_id = document.getElementById("process_id").value;
var length = value.length;
if (length <= 0) {
alert("Please Enter the sketch card");
window.location = 'sketch_screen.php';
} else {
window.location = 'dws_Support.php';
}
});
});
<form action="" method="post" autocomplete="off">
<div class="container">
<div class="alert alert-success" id="alert_box">
<input type="hidden" name="process_id" id="process_id" value="<?php echo $process_id; ?>">
<label>Enter the Sketch Card No :</label>
<input type=text id="txt_sketch_no" name="txt_sketch_no">
<input type=submit id="submit">
In the above code I would like to redirect the page with the help of Javascript, but window.location = 'dws_Support.php' in else part is not working, but when we alert with in the else part it gets displayed but not redirected to 'dws_Support.php'. Please help.
Try using
window.location.href='dws_Support.php'
you don't need form for redirecting with javascript ,problem come from your attribute action form, so use this code:
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var value = document.getElementById("txt_sketch_no").value;
var process_id = document.getElementById("process_id").value;
var length = value.length;
if (length <= 0) {
alert("Please Enter the sketch card");
window.location = 'sketch_screen.php';
} else {
window.location = 'dws_Support.php';
}
});
});
</script>
</head>
<body style="background-color: #73C5E1" >
<div class="container">
<div class="alert alert-success" id="alert_box">
<input type="hidden" name="process_id" id="process_id" value="12">
<label> Enter the Sketch Card No : </label>
<input type="text" id="txt_sketch_no" name="txt_sketch_no">
<input type = "submit" id="submit">
</div>
</div>
</body>
hope it help you.
Here is your fail: you are listening click, but submit event of the form brakes your logic. This is the fixed one:
$(document).ready(function() {
$("form").on('submit', function(e) {
e.preventDefault();
var value = document.getElementById("txt_sketch_no").value;
var process_id = document.getElementById("process_id").value;
var length = value.length;
if (length <= 0) {
alert("Please Enter the sketch card");
window.location = 'sketch_screen.php';
} else {
window.location = 'dws_Support.php';
}
});
});
glad if you found the answer, but there is no problem with your coding, you just missed the return false; after redirect..
<script src="jquery-1.4.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
$("#submit").click(function() {
var value = document.getElementById("txt_sketch_no").value;
var process_id = document.getElementById("process_id").value;
var length = value.length;
if (length <= 0) {
alert("Please Enter the sketch card");
window.location = '/sketch_screen.php';
return false;
} else {
window.location = 'dws_Support.php';
return false;
}
});
});
//-->
</script>
hope this can fix your problem. :)
I've picked up this code and it does not seem to work. The problem is the 'submit' button is not active when i try to click after i entered all the data to the form. Any help on where i am lacking? please
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="ourForm">
<label>First Name</label><input type="text" /><br />
<label>Last Name</label><input type="text" /><br />
<label>Email</label><input type="text" /><br />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function addEvent(to, type, fn){
if(document.addEventListener){
to.addEventListener(type, fn, false);
} else if(document.attachEvent){
to.attachEvent('on'+type, fn);
} else {
to['on'+type] = fn;
}
};
var Form = {
validClass : 'valid',
fname : {
minLength : 1,
maxLength : 15,
fieldName : 'First Name'
},
lname : {
minLength : 1,
maxLength : 25,
fieldName : 'Last Name'
},
validateLength : function(formEl, type){
if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
} else {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
}
},
validateEmail : function(formEl){
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formEl.value);
if (emailTest) {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
} else {
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
}
},
getSubmit : function(formID){
var inputs = document.getElementById(formID).getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'submit'){
return inputs[i];
}
}
return false;
}
};
addEvent(window, 'load', function(){
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm(){
var inputs = ourForm.getElementsByTagName('input');
if(Form.validateLength(inputs[0], Form.fname)){
if(Form.validateLength(inputs[1], Form.lname)){
if(Form.validateEmail(inputs[2])){
submit_button.disabled = false;
return true;
}
}
}
submit_button.disabled = 'disabled';
return false;
};
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
</script>
</body>
</html>
I copied the code and tried the same code. It works. It might be that you filled all the three inputs but you did not put correct EMAIL that fulfills the EMAIL format(regex) in the code.
For example try to fill inputs with these three inputs someone, someone, someone#gmail.com; Submit is enabled
Codeļ¼
<html>
<body>
<script>
window.onload = function () {
var do_not_drag = document.getElementsByClassName('no_select');
for (var i = 0; i < do_not_drag.length; i++) {
disableSelection(do_not_drag[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function () {
return false;
};
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function () {
return false;
};
}
}
function generateCaptcha() {
var captchaForRead = document.getElementById('captchaForRead');
var captchaForReadInnerHTML = Math.floor(Math.random() * 9000) + 1000
captchaForRead.innerHTML = captchaForReadInnerHTML;
captchaCorr = captchaForReadInnerHTML;
}
function verifyCaptcha(captchaInput) {
if (captchaInput == captchaCorr) {
document.write("Correct!")
}
}
</script>
<form onsubmit="verifyCaptcha(this.form.captchaInput.value);">
<p id="captchaForRead" class="no_select"></p>
<input type="text" name="captchaInput">
<input type="submit" value="submit">
</form>
<script>
generateCaptcha();
</script>
</body>
</html>
This is not working. What can i do? even after i inserted the correct captcha, nothing happened.
What can i do??? I've checked the javascript and html but still cannot find the problem.
Pls help.
Try this:
function verifyCaptcha(captchaInput){
console.log(captchaInput);
if (captchaInput==captchaCorr){
console.log('Correct');
}
}
<form onsubmit="verifyCaptcha(this.captchaInput.value);">
<p id="captchaForRead" class="no_select"></p>
<input type="text" name="captchaInput">
<input type="submit" value="submit">
</form>
I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>