JavaScript how to use for each - javascript

<!DOCTYPE html>
<html>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="errorTable" class="alert alert-danger alert-warning">
<!-- Validating City START -->
<div id="divname">
<tr>
<td width="3"></td>
<td width="23"><span class="table_row_error_text"><img id="imgsum" src="/images/error.gif" class="image" style="display: none;" ></span> </td>
<td width="5"></td>
<td><span class="table_row_error_text"> <span id="errorsum" /></span> </td>
</tr>
</div>
<!-- Validating City ENDS -->
<!-- Validating Zip Code START -->
<div id="divtype">
<tr>
<td width="3"></td>
<td width="23"><span class="table_row_error_text"><img id="imgdesc" src="/images/error.gif" class="image" style="display: none;" ></span> </td>
<td width="5"></td>
<td><span class="table_row_error_text"> <span id="errordesc" /></span> </td>
</tr>
</div>
<!-- Validating Zip Code ENDS -->
</table> Summary:
<input id="summaryOfAlert" type="text" />
<br>
<br> Description:
<input id="textarea3" type="text" />
<br>
<br> Save:
<input type="submit" onClick="return validateText()" /> </body>
<script>
function validateText() {
alert("Hi");
var summary = document.getElementById("summaryOfAlert").value;
var description = document.getElementById("textarea3").value;
var letters = /^[A-Za-z0-9._\-,\s]+$/;
var j;
j = 0;
if (summary != "") {
if (!summary.match(letters)) {
document.getElementById('errorsum').innerHTML = "In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display = 'block';
document.getElementById("imgsum").style.display = 'block';
j++;
}
}
if (description != "") {
if (!description.match(letters)) {
document.getElementById('errordesc').innerHTML = "In Description Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divtype").style.display = 'block';
document.getElementById("imgdesc").style.display = 'block';
j++;
}
}
if (j == 0) {
return true;
} else return false;
}
</script>
</html>
Above is a html/javascript code which I have developed for front end validation for special characters. it is working fine but my problem is whenever I entered special chars like <>%&(^ in both text fields and after submitting it is showing error message like as shown
In Summary Please Enter Only A-Za-z0-9-,.
In Description Please Enter Only A-Za-z0-9-,.
But when I removed special chars in one of the text fields and submitting the values again both error messages are displaying instead of only one error message

You are showing the messages but you are not hiding them anywhere. Try this:
if(!summary.match(letters)) {
document.getElementById('errorsum').innerHTML="In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display='block';
document.getElementById("imgsum").style.display='block';
j++;
} else {
document.getElementById('errorsum').innerHTML="";
document.getElementById("divname").style.display='none';
document.getElementById("imgsum").style.display='none';
}
And the same things for description. You could also make it a function so you don't have to write it twice.

Try This Code you should use else part to hide you message
function validateText() {
alert("Hi");
var summary = document.getElementById("summaryOfAlert").value;
var description = document.getElementById("textarea3").value;
var letters = /^[A-Za-z0-9._\-,\s]+$/;
var j;
j = true;
if(summary!="") {
if(!summary.match(letters)) {
document.getElementById('errorsum').innerHTML="In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display='block';
document.getElementById("imgsum").style.display='block';
j=false;
} else{j=true; document.getElementById("divname").style.display='none'; document.getElementById("imgsum").style.display='none';}
}
if(description!="") {
if(!description.match(letters)) {
document.getElementById('errordesc').innerHTML="In Description Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divtype").style.display='block';
document.getElementById("imgdesc").style.display='block';
j=false;
else{ j =true; document.getElementById("divtype").style.display='none'; document.getElementById("imgdesc").style.display='none';}
}
}
return j;
}
</script>

Related

Form gets submited even though JS function is returning false

Below is a code snippet I took from the html source:
<FORM id=SubmitLogon method=post name=submitLogonForm action=/MyLogin/SubmitLogon.do;jsessionid=reQYQqPCZt_6Oc3EkU66XFiC-fWQQ2DHPdCgWYwR5TbT9xsXOsPe!907086402 AutoComplete="off">
<TR>
<TD class=logonLabelTdTag>Username </TD>
<TD align=left>
<DIV id=wwgrp_username_Id class=wwgrp>
<DIV id=wwctrl_username_Id class=wwctrl>
<INPUT onchange="javascript: this.value=this.value.toUpperCase();" tabIndex=1 onfocus="javascript: this.value=this.value.toUpperCase();" id=username_Id class=logonTextBox maxLength=40 name=username>
</DIV>
</DIV>
</TD>
</TR>
<TR>
<SCRIPT language=JavaScript1.2 type=text/javascript>
$(document).ready(function () {
try {
$("input[type='text']").each(function(){
$(this).attr("autocomplete","off");
});
}
catch (e)
{ }
});
</SCRIPT>
<TD class=logonLabelTdTag>Password </TD>
<TD align=left>
<DIV id=wwgrp_password_Id class=wwgrp>
<DIV id=wwctrl_password_Id class=wwctrl>
<INPUT tabIndex=2 id=password_Id class=logonTextBox maxLength=40 type=password value="" name=password>
</DIV>
</DIV>
</TD>
</TR>
<TR>
<TD colSpan=2 align=right>
<BUTTON onclick=validateLoginCredentials() style="BORDER-TOP-STYLE: none; BORDER-LEFT-STYLE: none; HEIGHT: 39px; WIDTH: 98px; BACKGROUND: none transparent scroll repeat 0% 0%; BORDER-BOTTOM-STYLE: none; BORDER-RIGHT-STYLE: none" type=submit value="Loginn">
<IMG src="https://den02qoj.us.oracle.com/images/btn_login.jpg">
</BUTTON>
</TD>
</TR>
</FORM>
<script>
function validateLoginCredentials(){
alert('invoked');
var usernameVar = document.getElementById("username_Id").value;
var passwordVar = document.getElementById("password_Id").value;
//validationIdd_user
//validationIdd_password
alert('usernameVar is:'+usernameVar);
alert('passwordVar is:'+passwordVar);
alert('usernameVar length is:- '+usernameVar.length);
alert('passwordVar length is:- '+passwordVar.length);
document.getElementById("validationIdd").style.visibility = 'hidden';
document.getElementById("validationIdd_user").style.visibility = 'hidden';
document.getElementById("validationIdd_password").style.visibility = 'hidden';
if(usernameVar == '' && passwordVar == ''){
document.getElementById("validationIdd").style.display='';
alert('517-false');
return false;
}else if(usernameVar == '' || usernameVar == null){
document.getElementById("validationIdd").style.visibility = 'hidden';
document.getElementById("validationIdd_password").style.visibility = 'hidden';
document.getElementById("validationIdd_user").style.display='';
alert('523-false');
return false;
}else if(passwordVar == '' || passwordVar == null){
document.getElementById("validationIdd_password").style.display='';
alert('527-false');
return false;
}else{
alert('530-true submitting now----------------');
document.getElementById('SubmitLogon').submit()
return true;
}
alert('validateLoginCredentials:end');
}
</script>
First time click on submit button
When username(id:username_Id) and password(id:password_Id) both are empty the JS function validateLoginCredentials() it returned false this I verified by alert('517-false'); but form got submitted.
Again when I click on submit button for the second time
username(id:username_Id) and password(id:password_Id) both are empty the JS function validateLoginCredentials() is invoked but its not entering into the below block (which was the first scenario which I described above).
if(usernameVar == '' && passwordVar == ''){
document.getElementById("validationIdd").style.display='';
alert('517-false');
return false;
}
Why there is different results for the same (above) scenarios
and why form got submitted in first scenario even though JS function returned false?
Please help me out.
you have to put the check function in the form tag instead in the button like
<FORM id=SubmitLogon method=post onsubmit="return validateLoginCredentials()" name=submitLogonForm action=/MyLogin/SubmitLogon.do;jsessionid=reQYQqPCZt_6Oc3EkU66XFiC-fWQQ2DHPdCgWYwR5TbT9xsXOsPe!907086402 AutoComplete="off">

How to perform validation for Captcha using JavaScript?

I am new to UI design. I have created Captcha, Please anyone give me an idea to validate Captcha using JavaScript.Thanks in advance. I have added my code below.
Code for getting new Captcha:
<html>
<head>
<script language="javascript" type="text/javascript">
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 5;
var captchastring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum,rnum+1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
</script>
<style>
HTML Code:
</head>
<body onload="getCaptcha();">
<form name="randform">
<table style="border:1px solid #ecece4">
<tr><td colspan="2" align="center"><strong>Contact Us Form</strong></td></tr>
<tr><td>Enter Captcha Code</td><td><input type="text" id="txtcode"/></td></tr>
<tr>
<td>
</td>
<td>
<div id="captcha">
<div id="captcha_gen">
<label align="center" id="randomfield"></label>
</div>
</div><input type="button" value="Refresh" onClick="getCaptcha();"/></td></tr>
<tr><td colspan="2" align="center"><input type="button" value="Submit"/></td></tr>
</table>
</form>
</body>
<html>
function validateCaptcha()
{
var chr = document.getElementById("tbxCaptcha").value;
var cap = document.getElementById("randomfield").innerHTML;
if (chr==cap)
{
return true;
}
else
{
alert ("Please enter valid verification code");
return false;
}
}

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

Javascript Recipe Calculator, Hangs on isNan() Function?

I'm making a recipe calculator for my coursework. I have reached the stage where it will correctly validate everything and make a new row in a table. Sadly in the if statement within the recipe function, it always goes true for isNaN? No matter what I put? Can anyone help me with this?
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<script type="text/javascript">
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var ingredientcount = 0
// The save function
function save(){
var verified = true;
while(verified){
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if(serves === "" || name === "" || isNaN(serves)=== true)
{
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
}
else{
alert("sucess!");
// array(ingredient,amount,unit,name,serves)
return;
}
}
}
// The function to valiate the data and manage everything
function recipe(){
if(ingredient === ""|| amount === "" || unit === "Select Unit"){
alert("You must fill in all fields.")
}
else if(isNaN(amount)){
alert("You have to enter a number in the amount field")
}
else{
alert("hey!")
alert(recipe[1][2] + recipe[1][1])
var totalamount = amount + " "+ unit
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
ingredientcount ++;
alert(ingredientcount);
}
}
</script>
</head>
<body>
<h1>Recipe Name</h1>
<h2>Serves many people </h2>
<table border="1" id="table" >
<tr>
<td>
<input type="text" id="ingredient" placeholder="Enter an Ingredient">
</td>
<td>
<input type="text" id="number" placeholder="Enter an amount">
<select id="unit">
<option>Select Unit</option>
<option>Grams</option>
<option>Mililitres</option>
<option>Number</option>
</select>
</td>
<td>
<button type="button" onclick="recipe()">Add</button>
<button type="button" onclick="save()">Save</button>
</td>
</tr>
<th>Ingredient</th>
<th>Amount</th>
<th> </th>
</table>
</body>
</html>
The problem is that you are setting the values of ingredient, amount, and unit when the page loads, not when the Add button is pushed. You need to move those assignments to the recipe() function.

Alert box shows up multiple times on javascript

This is very simple code, and similar to my other question.
When I click submit, the alert box shows up three times for option one, twice for two, and once for three.
Here is the part of the code where the problem is most probably located:
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
And here is my whole code. It all works fine except for this.
<!-- saved from url=(0055)file:///C:/Users/Bartek/Downloads/Exam%20entry4.1.2.htm -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="file:///C:/Users/Bartek/Downloads/success.html">
<input type="radio" name="r1" value="GCSE">GCSE
<input type="radio" name="r1" value="AS">AS
<input type="radio" name="r1" value="A2">A2
<table width="50%" border="0">
<tbody>
<tr>
<td id="name" style="color: black; ">Name</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td id="subject" style="color: black; ">Subject</td>
<td>
<input type="text" name="subject">
</td>
</tr>
<tr>
<td id="enumber" style="color: black; ">Examination Number</td>
<td>
<input type="text" name="enumber">
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onclick=" return validateForm();">
</td>
<td>
<input type="reset" name="Reset" value="Reset">
</td>
</tr>
</tbody></table>
</form>
<script>
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.enumber.value.length != 4) {
msg += "The examination number must be exactly four characters long \n";
document.ExamEntry.enumber.focus();
document.getElementById('enumber').style.color = "red";
result = false;
}
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
if (msg == "") {
return result;
} {
alert(msg);
return result;
}
}
</script>
</body>
</html>
This is GCSE computing coursework.
for (var i = 0; i <len; i++) {
if (document. ExamEntry.r1[i].checked) {
chosen = document. ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
chosen won't be "" if it was set before; you don't set it back to "" if the item wasn't checked, and so it'll confirm the last one that was. Just merge them.
for(var i = 0; i < document.ExamEntry.r1.length; i++) {
if(document.ExamEntry.r1[i].checked) {
confirm(document.ExamEntry.r1[i].value);
}
}
You were missing an else.
if (!msg) {
return result;
} else {
alert(msg);
return result;
}

Categories