Pressing enter key submit the form? - javascript

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

Related

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=""

Form Field Submission

I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.

How to do validation for 10 digit mobile number Using jQuery

<div>
<span id="mobile-valid">
<i class="fa fa-check"></i>
Valid Mobile No
</span>
<span id="mobile-invalid" >
Invalid mobile No
</span>
</div>
<div>
Mobile No
</div>
<div>
<input id="mobile-num" type="text"/>
</div>
How to do validation for 10 digit mobile number Using jQuery Ajax?Only numbers are allowed cannot use characters or alphanumeric characters.So how can i use jquery Ajax to do validation.I want to show on above input box that Invalid Email .and (dont want to show alert)
This will work for you...
$(document).ready(function(){
$("#mobile-num").on("blur", function(){
var mobNum = $(this).val();
var filter = /^\d*(?:\.\d{1,2})?$/;
if (filter.test(mobNum)) {
if(mobNum.length==10){
alert("valid");
$("#mobile-valid").removeClass("hidden");
$("#folio-invalid").addClass("hidden");
} else {
alert('Please put 10 digit mobile number');
$("#folio-invalid").removeClass("hidden");
$("#mobile-valid").addClass("hidden");
return false;
}
}
else {
alert('Not a valid number');
$("#folio-invalid").removeClass("hidden");
$("#mobile-valid").addClass("hidden");
return false;
}
});
});
.hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mobile">
<div class="input">
<div class="label">
<div class="label-1">
<span id="mobile-valid" class="hidden mob">
<i class="fa fa-check pwd-valid"></i>Valid Mobile No
</span>
<span id="folio-invalid" class="hidden mob-helpers">
<i class="fa fa-times mobile-invalid"></i>Invalid mobile No
</span>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<div class="label-2">
Mobile No
</div>
</div>
<div class="col-xs-9">
<input id="mobile-num" type="text" class="form-control form-change-element" />
</div>
</div>
</div>
</div>
<form action="#">
Mobile number: <input type="text" name="mobile" pattern="^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$" title="Enter Valid mobile number ex.9811111111" required>
<input type="submit">
</form>
starting with 9,8,7 you can add more as well.
you can test it using https://regex101.com/
Valid number are.
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
Try this code in your jquery function
var mobileNum = $(this).val();
var validateMobNum= /^\d*(?:\.\d{1,2})?$/;
if (validateMobNum.test(mobileNum ) && mobileNum.length == 10) {
alert("Valid Mobile Number");
}
else {
alert("Invalid Mobile Number");
}
Try this code. It contains the ten digits number validation for mobile:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
body
{
padding: 10px;
font-family: Arial;
Font-size: 10pt;
}
span
{
font-weight:bold;
}
.san{
height: 26px;
width: 250px;
border: 1px solid #9E9E9E;
padding: 5px;
border-radius: 5px;
margin: 10px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$('#txtPhone').blur(function(e) {
if (validatePhone('txtPhone')) {
$('#spnPhoneStatus').html('Valid Mobil Number');
$('#spnPhoneStatus').css('color', 'green');
}
else {
$('#spnPhoneStatus').html('Invalid Mobile Number');
$('#spnPhoneStatus').css('color', 'red');
}
});
});
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /[1-9]{1}[0-9]{9}/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
});//]]>
</script>
</head>
<body>
Phone Number: <input type='text' id='txtPhone' class="san" maxlength="10"/>
<span id="spnPhoneStatus"></span>
</body>
</html>
try such thing
var value = "1234567.....";
var NumberRegex = /^[0-9]*$/;
if(value.length <= 10){
if(NumberRegex.test(value)){
//do whatever you want to
}else{
alert('invalid')
}
}
Jquery validation for mobile number using regular expression
Validation include:
10 digit number only (No alphabets and No special characters)
Numbers starts from 6,7,8,9
<html>
<body>
<label>Mobile Number:</label>
<input type="text" class="form-control mobile-valid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.mobile-valid').on('keypress', function(e) {
var $this = $(this);
var regex = new RegExp("^[0-9\b]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
// for 10 digit number only
if ($this.val().length > 9) {
e.preventDefault();
return false;
}
if (e.charCode < 54 && e.charCode > 47) {
if ($this.val().length == 0) {
e.preventDefault();
return false;
} else {
return true;
}
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
</script>
</body>
</html>
For Demo Click here!
var pattern= /^[0]*(\d{9})*\s*$/;
Use this pattern only to validate Sri Lankan numbers. In above code line only validate mobile number starting with 0.

My javascript stops working after ajax response

For some reason my javascript stops working after I have submitted a POST request.
Here is what is happening. I load my webpage, fill out the form and click 'Click me' :
Next I click ok in the alert popup and the expected result appears:
I fill out the form, but when I try to click the button nothing happens!
Not even my alert popup.
Here are the files I am using.
My CSS, simple2.css :
body, html {
margin:0;
padding;
height:100%
}
a {
font-size:1.25em;
}
#content {
padding:25px;
}
#fade {
display: none;
position:absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #ababab;
z-index: 1001;
-moz-opacity: 0.8;
opacity: .70;
filter: alpha(opacity=80);
}
#modal {
display: none;
position: absolute;
top: 45%;
left: 45%;
width: 64px;
height: 64px;
padding:30px 15px 0px;
border: 3px solid #ababab;
box-shadow:1px 1px 10px #ababab;
border-radius:20px;
background-color: white;
z-index: 1002;
text-align:center;
overflow: auto;
}
#results {
font-size:1.25em;
color:red
}
My HTML, simple2.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="simple2.css">
<title>simple II</title>
</head>
<body>
<div id="fade"></div>
<div id="modal"> <img id="loader" src="images/loading.gif" /> </div>
<div id="results"><!-- Results are displayed here -->
<form method="post" name="start" target="_blank">
<p>Enter thing1: <input type="text" id="thing1" name="thing1" size="10" /></p>
<p>Enter thing2: <input type="text" id="thing2" name="thing2" size="10" /></p>
<p>Enter thing3: <input type="text" id="thing3" name="thing3" size="10" /></p>
<p>Check thing4: <input type="checkbox" id="thing4" name="thing4" value=1>
<input type="hidden" id="state" name="state" value="one" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?0000000000015"></script>
</div>
</body>
</html>
My javascript, simple2.js :
function openModal() {
document.getElementById('modal').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
document.getElementById('fade').style.display = 'none';
}
function loadAjax(url,data, app, epoch, state) {
console.log ("loadAjax urls is [" + url + "] data is [" + data + "]" );
// document.getElementById('results').innerHTML = '';
console.log ("line 14");
openModal();
console.log ("line 16");
var xhr = false;
console.log ("line 18");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
closeModal();
console.log ("line 28");
document.getElementById("results").innerHTML = xhr.responseText;
}
}
console.log ("line 32");
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
console.log ("line 35");
}
}
document.querySelector("#results button").addEventListener("click", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
});
... and finally my cgi script, simple2.py :
#!/usr/bin/env python
import cgi
import os
#import cgitb
import cgitb; cgitb.enable() # for troubleshooting
import time
import calendar
def goto_state_two( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<p>Enter thing5: <input type="text" id="thing5" name="thing5" size="10" /></p>
<p>Enter thing6: <input type="text" id="thing6" name="thing6" size="10" /></p>
<p>Enter thing7: <input type="text" id="thing7" name="thing7" size="10" /></p>
<p>Check thing8: <input type="checkbox" id="thing8" name="thing8" value=1>
<input type="hidden" id="state" name="state" value="two" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
def goto_done( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<input type="hidden" id="state" name="state" value="done" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
form = cgi.FieldStorage()
state = form.getvalue("state")
if state == 'one' :
thing1 = form.getvalue("thing1", "")
thing2 = form.getvalue("thing2", "")
thing3 = form.getvalue("thing3", "")
thing4 = form.getvalue("thing4", "")
goto_state_two( thing1, thing2, thing3, thing4 )
elif state == 'two' :
thing5 = form.getvalue("thing5", "")
thing6 = form.getvalue("thing6", "")
thing7 = form.getvalue("thing7", "")
thing8 = form.getvalue("thing8", "")
goto_done( thing5, thing6, thing7, thing8 )
elif state == 'done' :
print """
Hurray you did it!<br>
"""
else:
print """
unknown state [%s]
<hr>
""" % ( state )
document.getElementById("results").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "BUTTON") {
// Move Prevent Default into condition to allow
// other events to bubble.
e.preventDefault();
// This is a Button click we have captured
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
}
});

Why does the search button in my jsp code not work?

Following is the code of my jsp where there are two input fields regNo and studentName.
I want the user to enter only numbers in regNo field. It should not contain any spaces and the length of the digits should be only 12.
I added the check for characters and I added CSS and now my Search button isn't working.
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
#mycontainer, h1, h3 {
text-align:center;
}
form {
display:inline-block;
}
#errorMsgNumber {
display: none;
background: brown;
color: white;
}
</style>
<script>
var regNoField = document.getElementById('regNo');
var regNoMessage = document.getElementById('regNoErrorMsgNumber');
var inputFieldsButton = document.getElementById('inputFields');
regNoField.addEventListener('keydown', onChange);
function onChange(e) {
if (e.keyCode < 48 || e.keyCode > 57) {
regNoMessage.style.display = 'block'
};
if(/^\d+$/.test(regNoField.value)) {
inputFieldsButton.disabled = false;
} else {
inputFieldsButton.disabled = true;
}
}
$(document).ready(function(){
$('#inputFields').click(function(event){
if (document.getElementById('regNo').value !=""){
$("#number").submit();
}else if(document.getElementById('studentName').value !=""){
$("#name").submit();
}
});
});
</script>
</head>
<body>
<div id="mycontainer">
<form method="post" action="number" id="number">
<div id="regNoErrorMsgNumber">Only numbers are allowed</div>
<div style="text-align: center;" >
<!-- //TODO: Only number, no spaces, no special symbol and 12 digit check-->
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"> OR
</div>
</form>
<form method="post" action="name" id="name">
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
</form>
</div>
<div style="text-align: center;">
<input id="inputFields" type="button" value="Search" />
</div>
</body>
I made little modification in your code. It was the ordering of javascript code. I have put your java script code after the elements. Now it will work.
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
#mycontainer, h1, h3 {
text-align:center;
}
form {
display:inline-block;
}
#errorMsgNumber {
display: none;
background: brown;
color: white;
}
</style>
</head>
<body>
<div id="mycontainer">
<form method="post" action="number" id="number">
<div id="regNoErrorMsgNumber">Only numbers are allowed</div>
<div style="text-align: center;" >
<!-- //TODO: Only number, no spaces, no special symbol and 12 digit check-->
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"> OR
</div>
</form>
<form method="post" action="name" id="name">
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
</form>
</div>
<div style="text-align: center;">
<input id="inputFields" type="button" value="Search" />
</div>
</body>
<script>
var regNoField = document.getElementById('regNo');
var regNoMessage = document.getElementById('regNoErrorMsgNumber');
var inputFieldsButton = document.getElementById('inputFields');
regNoField.addEventListener('keydown', onChange);
function onChange(e) {
if (e.keyCode < 48 || e.keyCode > 57) {
regNoMessage.style.display = 'block'
};
if(/^\d+$/.test(regNoField.value)) {
inputFieldsButton.disabled = false;
} else {
inputFieldsButton.disabled = true;
}
}
$(document).ready(function(){
$('#inputFields').click(function(event){
if (document.getElementById('regNo').value !=""){
$("#number").submit();
}else if(document.getElementById('studentName').value !=""){
$("#name").submit();
}
});
});
</script>
You can do one more thing instead of referring the jquery from website itself you can refer the google hosting look at the link for the benefit http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/

Categories