JQuery keypress function not working - javascript

I have the following code which checks if a roll number is valid in the database selected by the postname variable. It was working in an earlier version where I hadn't introduced the second variable postname. But at the moment, this code is not working. What's the error here?
$(document).ready(function() { //function to check rollno is valid
$('#roll').keyup(function(event) {
var rolll=$('#roll').val();
var postname=$('#post').val();
$.get('CheckRollValidity',{roll:rolll},{post:postname},function(responseText) {
$('#status1').text(responseText);
});
});
});
Servlet
roll = request.getParameter("roll");
temp = request.getParameter("post");
table1 = "dbo."+post;
table2 = "dbo.user_candidates";
try
{
if (roll.length() < 10 || roll.length() > 10) {
result = "Please enter your " + len + "-digits roll number.";
count1 = 1;
}
else if (!roll.matches("[0-9]*"))
{
result = "Please enter digits only";
count1 = 1;
}
if (count1 == 0)
{
//database work
result="OK";
}
else
{
result = "Error";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result);
Also, can I do the same via ajax, alternatively? Here I don't want the code working on pressing a submit button. Rather the working is happening on keypress.

You can't send two objects, you'll have to use one object with two values otherwise the second object is seen as the argument which should have been the callback
$.get('CheckRollValidity',{roll:rolll, post:postname},function(responseText) {
$('#status1').text(responseText);
});

Related

JavaScript validation not working in installshield

Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}

Need to get indexes from array and output them to user in JavaScript

We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;

javascript: counting digits in a text input

I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}

Set cookie and display in new page

function form()
{
var formVal1=document.forms ["form1"]["num1"].value;
var formVal2=document.forms ["form1"]["num2"].value;
if ( formVal1<1 || formVal1>100)
{
alert("Please enter a value between 1-100");
document.form1.num1.focus() ;
return false;
}
else if ( formVal2<1 || formVal2>100)
{
alert("Please enter a value between 1-100");
document.form1.num2.focus() ;
return false;
}
var sum= ((document.forms ["form1"]["num1"].value - 0 ) + (document.forms ["form1"]["num2"].value - 0));
alert("Sum of two numbers:" +sum);
if(sum>0)
{
var fromVal3=prompt("Please enter the third value:");
if(fromVal3<1 || fromVal3>5)
{
alert("Please enter a value between 1-5");
document.form1.num3.focus() ;
return false;
}
var Mul=fromVal3*sum;
alert("Multiplied Value:" +Mul);
}
if(typeof(Storage)!=="undefined")
{
document.cookie=Mul;
alert(document.cookie);
var allcookies=document.cookie;
document.write(allcookies);
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
}
it is a javascipt form hmtl page to take two inputs and prompts for the third and it will multiply with sum of first two numbers and sets the result as cookie and must display the cookie on new page. can anyone help me with setting a cookie and displaying it on new page??
To set javascript cookie you need something like this
document.cookie="username=John";
or
document.cookie="username=Joh"; expires=...; path=...";
So, in your example, it would be something like:
document.cookie='Mul='+Mul;
As far as getting cookies goes, all you have is document.cookie which will look something like a=b; c=d; e=f which means that you need to split few times to get what you need. Something like this:
var c = document.cookie.split('; ');
for (i=0;i<c.length;i++) {
var cookie = c[i].split('=');
if (cookie[0]=='Mul') {
var myCookie = cookie[1];
break;
}
}
After this, you will have your cookie stored in myCookie variable.

Validate email as you type

I want to validate input as I type so I use onkeyup event to do so, but if I validate an email regex "name#domain.com", as soon as user starts to type it throws an error - first character doesnt match regex...
So I wrote this:
var addValidation = function (patterns) {
var index = patterns.length; //I know I can avoid this
while (index--) {
patterns[index] = new RegExp(patterns[index]);
}
index = 0;
var current = patterns[index],
matchExact = function (patt, str) {
var match = str.match(patt);
return match !== null && str === match[0];
};
return function () {
var str = this.value;
if (!matchExact(current, str) ) {
var tmp = patterns[index + 1] ?
new RegExp(current.source + patterns[index + 1].source) :
false;
if (tmp && matchExact(tmp, str)) {
current = tmp;
index++;
}
else {
alert("Wrong");
}
}
}
};
document.getElementById("x").onkeyup = addValidation(["[a-zA-Z0-9\\.]+", "#{1}", "[a-zA-Z0-9]+", "\\.{1}", "[a-zA-Z]{1,3}"]);
It seems to work, but... it's ugly and it will alert you if you do step back (eg. "name#" and you press backspace).
I know that Dojo's validation is great, but I do not want to use Dojo. Are there any better ways to achieve that?
//EDIT: http://livedocs.dojotoolkit.org/dijit/form/ValidationTextBox this is an example, but you can define your own pattern (like email regex) and it will validate it perfectly.
Add interval before validation will start:
var t;
document.getElementById("x").onkeyup = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
//do validation
}, 1000)
}
Don't ever try to validate an email address with a regualr expression. You'll either end up allowing addresses which are not valid, or block email addresses which are perfectly valid and just annoy your visitors. It's also worth bearing in mind that the best regex so far for validating email addresses is this:
http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Categories