Captcha Code in JavaScript is not working - javascript

I have a validation Form using Javascript. It must validate the name, email and captcha. But through my validation function, the name and email are validated but the captcha is not validated after the onclick of the submit button.
The following functions shows my code:
<script type="text/javascript">
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
} </script>
The following is my html code for the form which i am using:
<form class="form-horizontal" role="form" action='<?php echo
site_url(); ?>/Welcome/insert_support_info' method="post" enctype="multipart/form-data" onsubmit="return validateform()" name="supportus_form">
<br style="clear:both"/>
<h3 style="margin-bottom: 25px; text-align: center;"><u>Let us Know your Interest</u></h3>
<div class="form-group">
<input type="text" class="form-control" name="cm_name" id="fullname" placeholder="Enter Your Name"/>
<input type="text" class="form-control" name="cm_email" id="email" placeholder="Enter Your E-Mail"/>
<input type="text" class="form-control" name="cm_phone" id="phone" placeholder="Enter Your Phone Number or Mobile Number"/>
<textarea class="form-control" name="cm_message" id="message" rows="3" placeholder="Add your Query"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">Limit - 100 words</p></span>
<input class="form-control" name="datetime" value="<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time()); echo $date;
?>" type="hidden" />
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<button type="submit" class="btn btn-success">Submit</button>
</div>
<hr/>
</form>
I have kept the css to show up the captcha form
<style>
.capbox {
background-color: #92D433;
border: #B3E272 0px solid;
border-width: 0px 12px 0px 0px;
display: inline-block;
*display: inline; zoom: 1; /* FOR IE7-8 */
padding: 8px 40px 8px 8px;
}
.capbox-inner {
font: bold 11px arial, sans-serif;
color: #000000;
background-color: #DBF3BA;
margin: 5px auto 0px auto;
padding: 3px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaDiv {
font: bold 17px verdana, arial, sans-serif;
font-style: italic;
color: #000000;
background-color: #FFFFFF;
padding: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaInput { margin: 1px 0px 1px 0px; width: 135px; }
</style>
With the Above code, the captcha is not working. I am using captcha for the first time.

Hey You are using conditional tags in improper way . That leads to unknown bugs. Following Javascript code works you correct.
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
var captha = document.getElementById("txtCaptcha").value;
var capthaValue = document.getElementById('CaptchaInput').value.replace(/ /g,'');
console.log(typeof captha);
if(capthaValue == "" || captha != capthaValue) {
validCaptcha()
}
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
function validCaptcha() {
var why = "";
if(capthaValue == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(capthaValue != ""){
if((captha != capthaValue) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;

Related

Use JS to determine if all form fields are filled and correctly

*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>

Unable to redirect my form to a new html page. Its going to localhost:3000/confirm.html instead i want it to open confirm.html in a new window

In the below code, after clicking on 'Save Data' I want the page to go to another htm page 'confrim.html'. Instead what is happening is its just showing "localhost:3000/confirm.html" and not opening a new page. Can anyone help to fix this, attaching the code for the reference.
I tried to implement the following through the submitInfo() function
Thanks
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">-->
<style>
* {
box-sizing:border-box;
border-color: teal;
}
html{
background : radial-gradient(rgba(48, 97, 97, 0.5),rgba(255,255,255,0.5))
}
div {
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
.input[type=button]{
font: 25px Calibri;
width: auto;
float: left;
cursor: pointer;
padding: 7px;
color: teal;
font-size: 30px;
}
#bt{
width : 190px;
height: 60px;
font-size: 25px;
font-family: 'Times New Roman', Times, serif;
background-color: #05193d;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin-top: 10px;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color:teal
}
</style>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<!--<link rel="stylesheet" href="style.css">-->
</head>
<body>
<div>
<form name="myForm" action="confirm.html" method="POST" >
<!--Add few elements to the form-->
<div>
<label for="Name">Name</label>
<input type="text" id="txtName" placeholder="Enter your name" required />
</div>
<div>
<label for="Email">Email</label>
<input type="text" id="txtEmail" placeholder="Enter your Email Id" />
</div>
<div>
<label for="Controller Type">Controller Type</label>
<select id="selProd">
<option value=""> - Select the Controller - </option>
<option value="RAID">RAID</option>
<option value="JBOD">JBOD</option>
<option value="EBOD">EBOD</option>
<option value="AP">AP</option>
</select>
</div>
<div>
<label for="Test Type">Test Type </label>
<select id="selTest">
<option value=""> - Select The Test - </option>
<option value="BFT">BFT</option>
<option value="Manufacturing">Manufacturing</option>
<option value="Channel">Channel</option>
<option value="DVT" >DVT</option>
</select>
</div>
<div>
<label for="Protocol Type">Protocol Type </label>
<select id="selProto">
<option value=""> - Select The Protocol - </option>
<option value="SAS">SAS</option>
<option value="iSCSI">iSCSI</option>
<option value="FC">FC</option>
</select>
</div>
<div>
<label for="IP Address">IP Address:</label>
<input type="text" id="txtIP" placeholder="Enter your IP address" />
</div>
<div>
<label for="Chasis Input">Number of Chasis Input:</label>
<input type="number" id="txtInputs" placeholder="Enter Number of Chasis" />
</div>
<div>
<input type="button" id="myBtn" value="Save data" onclick="submitInfo()"/>
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</form>
</div>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const email = document.getElementById('txtEmail');
const test = document.getElementById('selTest');
const product = document.getElementById('selProd');
const protocol = document.getElementById('selProto');
const IP = document.getElementById('txtIP');
const Inputs = document.getElementById('txtInputs');
// This variable stores all the data.
let data =
'\rName : ' + name.value + '\r\n' +
'Email ID : ' + email.value + '\r\n' +
'Test Type : ' + test.value + '\r\n' +
'Product Type : ' + product.value + '\r\n' +
'Protocol Type : ' + protocol.value + '\r\n' +
'IP Address : ' + IP.value + '\r\n' +
'Chasis Inputs : ' + Inputs.value;
if(name.value =='' || email.value == '' || test.value =='' || product.value =='' || IP.value == ''|| Inputs.value == ''){
alert("Please fill all the fields!");
return;
}
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == false)
{
alert('Invalid Email Address');
return false;
}
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(IP.value) == false)
{
alert('Invalid IP Address');
return false;
}
if(name.value.length<3){
alert("Name must be having atleast 3 Characters");
return;
}
if(name.value == ''){
alert("Enter the name First");
}
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.yaml'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
var disable_options = false;
document.getElementById('selProd').onchange = function () {
//alert("selected value = "+this.value);
if(this.value == "RAID")
{
document.getElementById('selProto').removeAttribute('disabled');
}
else
{
document.getElementById('selProto').setAttribute('disabled', true);
}
}
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if(product == "EBOD" && test== "BFT"){
window.location ="confirm.html";
}
}
</script>
</body>
</html>
You could use the window.open method - like so:
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if( product == "EBOD" && test== "BFT" ){
window.open( "confirm.html", "Confirm", "fullscreen=yes,location=no,menubar=yes,resizable=no,scrollbars=no,status=no,toolbar=no" );
}
}
you have a
<form name="myForm" action="confirm.html" method="POST" >
which, on form submit, your browser will look for confirm.html file. I don't know whether you have file named confirm.html, but I think you do. otherwise it'll show 404 error.
As you instructed in your form, browser'll look for confirm.html, and on redirect, it'll show what's in confirm.html file.
you should remove your js script from this file and put it inside confirm.html file. or just replace action="confirm.html" with action=""

event handler, broken page

The page should output and execute a temperature converter...
However,
While I'm wanting to test my program, I keep running into this a blank page type error...
can someone kind of proof read this, because I don't know what I'm missing.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var convertTemp = function(){
var f;
var c;
if($("to_Celsius").checked){
f = parseFloat($("degrees_entered").value);
if(isNaN(f)){
alert("please type in a value ");
}
else{
c = (f-32) * 5/9;
$("degrees_computed").value = c.toFixed(0);
}
}
else{
c = parseFloat($("degrees_entered").value);
if(isNaN(c)){
alert("you must enter a valid number for degrees.");
}
else{
f = c * 9/5 + 32;
$("degrees_computed").value = f.toFixed(0);
}
}
};
var toFahrenheit = function(){
$("degree_label_1").firstChild.nodeValue = "Enter C degrees:";
$("degree_label_2").firstChild.nodeValue = "Degrees F";
clearTextBoxes();
$("degrees_entered").focus();
};
var toCelsius = function(){
$("degree_label_1").firstChild.nodeValue = "Enter F degrees: ";
$("degree_label_2").firstChild.nodeValue = "Degrees C: ";
clearTextBoxes();
$("degrees_entered").focus();
};
var clearTextBoxes = function(){
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function(){
$("convert").onclick = convertTemp;
$("to_Celsius").onclick != toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
toCelcius != toCelsius ?
Is that it? A silly typo? The rest looks fine... also watch casing. In your JS you have to_Celsius... but in the html... to_celcius... bad habit for sure
Some issues I verified:
in the line if($("to_Celsius").checked){ you refer to to_Celsius id, but it should be to_celsius (lowercase);
in the lines:
$("to_Celsius").onclick = toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
Same thing. Replace both the id with to_celsius and to_fahrenheit.
in this line var toCelcius = function(){, the function is named toCelcius. Just rename it to toCelsius (with s).
Working code: https://jsfiddle.net/mrlew/p8w111ms/

If I add new form elements (appendChild) a form, I can't add event

I made a program when you enter form field number, you can insert a plus input box if you fell, whem remove. A problem is that we have a for loop, where you can gather elements which the "validate" class is (these form fields). onblur event to add functions, but I can not solve that added new elements to the program take into account. I tried and I did arrays that included new elements into an array, but since the for loop is therefore outside the event, if you add it, you can do nothing happens.
If anyone can help that in that case, it wont solve this, I really appreciate it!
(A code is supplied, only a test, specifically focuses on this problem.)
function onlyNumber(e) {
var x = e.keyCode;
if ((x >= 49 && x <= 57) || x === 9 || x === 8 || x === 46 || (x >= 97 && x <= 105)) {
return true;
} else {
e.preventDefault();
}
}
function initOnlyNumber() {
var el = document.querySelectorAll('.onlynumber');
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('keydown', onlyNumber, false);
}
}
var childNumber = document.querySelector('.childNumber');
childNumber.onkeyup = function() {
var childNumberValue = childNumber.value;
var childrens = document.querySelector('.childrens');
var inputLengths = document.querySelectorAll('.kids');
var inputLength = '';
var element = '';
for (var i = 0; i < inputLengths.length; i++) {
var inputLength = inputLengths.length;
var element = inputLengths[i];
}
var arrayElement = [];
for (var i = inputLength; i < childNumberValue; i++) {
var newElement = document.createElement('input');
newElement.classList.add('kids');
newElement.classList.add('validate');
newElement.setAttribute('name', 'child-' + (i + 1));
newElement.setAttribute('data-name', 'child-' + (i + 1));
childrens.appendChild(newElement);
}
if (inputLength == 1) {
if (childNumberValue == '') {
childrens.removeChild(childrens.lastChild);
}
}
if (childNumberValue > 0) {
for (var i = inputLength; i > childNumberValue; i--) {
childrens.removeChild(childrens.lastChild);
}
}
}
var validates = document.querySelectorAll('.validate');
for (var i = 0; i < validates.length; i++) {
var validate = validates[i];
validate.onblur = function(event) {
obj = this;
console.log(obj);
}
}
window.onload = function() {
initOnlyNumber();
}
body {
margin: 20px;
padding: 0;
}
*:link,
*:hover,
*:visited,
*:focus {
outline: none;
}
input:-webkit-autofill {
color: #fff;
-webkit-box-shadow: 0 0 0px 1000px #4caf50 inset;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input {
background-color: #4caf50;
border: 1px solid #555;
color: #fff;
padding: 10px;
width: 50px;
}
.childrens {
display: inline-block;
}
.childrens input {
display: inline-block;
margin-left: 15px;
}
.childNumber {
background-color: #555;
}
<form action="">
<input class="validate onlynumber" name="name" type="text">
<br />
<br />
<input class="validate onlynumber" name="email" type="text">
<br />
<br />
<input class="validate onlynumber" name="tax" type="text">
<br />
<br />
<input class="validate onlynumber" name="phone" type="text">
<br />
<br />
<input class="childNumber onlynumber" name="childNumber" type="text" maxlength="1">
<div class="childrens"></div>
</form>

Pressing enter key submit the form?

HTML code:
<html>
<head>
<title>Registration Form</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/style.css">
<script>
function submitAlbum(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
alert("condition1 is ..."+str1);
alert("condition2 is ..."+str2);
alert("condition3 is ..."+str1 == str2);
if (str1 == str2)
{
//alert("Entered captcha is correct");
}
else{
alert("Entered captcha is wrong");
document.getElementById("txtInput").value="";
return false;
}
var frm=document.getElementById("custRegistration");
frm.action="CustomerinfoServlet?formidentity=doRegistrations";
frm.submit();
}
</script>
</head>
<body style=" background-color:#f9f9f9" onload="DrawCaptcha();">
<div style="width: 100%; background-repeat:no-repeat; margin-top:30px; height:546px; background-image: url('images/mac.png')">
<br/><br/>
<div style="margin: 0 auto; background-color: #ffffff; opacity:0.9; border: 1px solid #D7EBFF; width: 400px; padding: 15px; height: 440px; margin-left: 56%;">
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="name">
<label for="name">Name <span style="color:red">*</span>:</label>
<input type="text" name="name" id="name" placeholder="" pattern="[A-Za-z ]{3,20}" required/>
<input type="hidden" id="formidentity" name="formidentity" value="doRegistrations"/>
</p>
<p class="email">
<label for="email">Email Id <span style="color:red">*</span>:</label>
<input type="email" name="email" id="email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|org|net|us|info|biz|co)" required aria-required="true" placeholder="" required/>
</p>
<p class="Captcha" style="margin-top:5%; width: 100%;">
<div style="margin:0 0 0 1%">
<label class="captchalabel" style="width:38%; float: left;"><span style="margin:0 0 0 9%">Enter the text </span> <span style="color:red">*</span>:</label>
<input type="text" name="txtInput" id="txtInput" style="float: left;" required/> </div>
<div style="width: 20%; float: right;">
<input type="text" id="txtCaptcha" style="background-color:#E7EBF5; text-align:center; margin: 19px 104px 0px 0px; width: 120px; border-radius:0px; border:1px solid #ccc; font-weight:bold; font-family:Arial; " />
<input type="image" id="btnrefresh" onclick="DrawCaptcha();" src="images/captcha.png"/>
</div>
</p>
<p class="submit">
<input type="submit" value="Submit" />
</p>
</form>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.realperson.js"></script>
<script type="text/javascript">
//Created / Generates the captcha function
function DrawCaptcha()
{
var a = Math.floor(Math.random() * 10)+ '';
var b = Math.floor(Math.random() * 10)+ '';
var c = Math.floor(Math.random() * 10)+ '';
var d = Math.floor(Math.random() * 10)+ '';
var e = Math.floor(Math.random() * 10)+ '';
var f = Math.floor(Math.random() * 10)+ '';
var g = Math.floor(Math.random() * 10)+ '';
var code = a + ' ' + b + ' '+ c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("txtCaptcha").value = code
}
// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
return string.split(' ').join('');
}
</script>
</html>
In this I have an issue. The problem is whenever I enter any text in the captcha textbox and press enter key. Then the captcha code is changing, ie, numbers are refreshing.
Also form is getting submit and getting the message ('captcha is wrong').
Can anyone tell me how to stop form submit when we press enter key after entering captcha in textbox?
Well you could disable the Enter button on the captcha input field using jQuery.
An example being:
$('#txtInput').bind("keypress", function (e) {
if (e.keyCode == 13) return false;
});
Where keyCode == 13 is the Enter key
Update
To add the above code in your file, just copy and paste this into your html:
<script type="text/javascript">
$(document).ready(function(){
$('#txtInput').bind("keypress", function (e) {
if (e.keyCode == 13) return false;
});
});
</script>
You can do this using the following jQuery code:
$('#custRegistration').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
LOL :)
AS dfsq said in comment:
"Why do you press Enter if you don't want to submit the form?"
But to block sending form with enter on input do this:
$('body').on('keydown', '#chaptcha_input', function(e) {
if(e.which == 13 && !e.shiftKey) {
e.preventDefault();
}
});
Try this
$('#txtInput').on("keyup",function(e){
if(e.keyCode == 13)
return false;
// do your stuff here if not enter key pressed
});

Categories