validation form in table mode with javascript - javascript

i made my form in table mode
like this:
<form name="register" method="post" action="#" onSubmit="return validasi()">
<table width="507" border="0">
<h1 class="title">Form Perubahan Password</h1>
<tr>
<td width="190" ><span id="usernameerror" class="style20">Masukkan Username </span></td>
<td width="319"><input name="username" type="text"></td>
</tr>
<tr>
<td><span id="passworderror" class="style20">Masukkan Password Lama</span></td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td><span id="password1error" class="style20">Masukkan Password Baru</span></td>
<td><input name="pass1" type="password"></td>
</tr>
<tr>
<td><span id="password2error" class="style20">Ulangi Masukkan Password Baru</span></td>
<td><input name="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
and this my validation code with javascript. check it out..
<script language="javascript">
function checkName(register)
{
var eobj = document.getElementById('usernameerror');
var susername = register.username.value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
eobj.innerHTML = '';
if (susername == '') {
error = 'Error: Username tidak boleh kosong';
register.username.focus();
}
else if (!oRE.test(susername))
{
error="Salah format";
}
if (error)
{
register.username.focus();
eobj.innerHTML = error;
return false;
}
return true;
}
function validatePwd(register) /* old password verification */
{
var eobj = document.getElementById('passworderror');
var invalid = ' ';
var pw = register.pass.value;
var error = false;
eobj.innerHTML = '';
if (pw.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass.focus();
eobj.innerHTML = error;
return false
}
return true;
}
function validatePwd1(register) /* password & retype-password verification */
{
var eobj1 = document.getElementById('password1error');
var eobj2 = document.getElementById('password2error');
var invalid = ' ';
var pw1 = register.pass1.value;
var pw2 = register.pass2.value;
var error = false;
eobj1.innerHTML = '';
eobj2.innerHTML = '';
if (pw1.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass1.focus();
eobj1.innerHTML = error;
return false
}
if (pw1 != pw2)
{
eobj2.innerHTML = ' password tidak sama, coba masukkan kembali password anda';
return false;
}
return true;
}
function validasi()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
When i use this validation in usually form its work But in table mode that's validation code doesn't work..help me to solve this problem...tq
view demo
http://jsfiddle.net/andricoga/u9eZz/

You have declared onSubmit="return validasi()" in form , but where you defined function for that. for validation working you need to define function for that.
function validasi(){
// validation code goes here
}

In your validatePwd() function replace
eobj1.innerHTML = error;
with
eobj.innerHTML = error;
you have not defined this eobj1 object and hence it is causing a run time javascript error.

I changed the code to display the error beside the field, try this out
Javascript
<script language="javascript">
function checkName()
{
var obj = document.getElementById('usernameerror');
var susername = document.getElementById('username').value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
obj.innerHTML = '';
if (susername == '') {
error = 'Username can not be empty';
}
else if (!oRE.test(susername))
{
error = 'One format';
}
if (error)
{
document.getElementById('username').focus();
obj.innerHTML = error;
return false;
}
return true;
}
function validatePwd() /* password & retype-password verification */
{
var obj = document.getElementById('pwderror');
var invalid = ' ';
var pw = document.getElementById('pass').value;
var error = false;
obj.innerHTML = '';
if (pw.length < 1)
{
error = 'Enter your old password';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass').focus();
obj.innerHTML = error;
return false
}
return true;
}
function validatePwd1() /* password & retype-password verification */
{
var obj = document.getElementById('pwd1error');
var invalid = ' ';
var pw1 = document.getElementById('pass1').value;
var pw2 = document.getElementById('pass2').value;
var error = false;
obj.innerHTML = '';
if (pw1.length < 1)
{
error = 'Enter your new password';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass1').focus();
obj.innerHTML = error;
return false
}
if (pw1 != pw2)
{
obj.innerHTML = 'passwords are not the same, try to re-enter your password';
return false;
}
return true;
}
function validate()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
Form
<form name="register" method="post" action="#" onSubmit="return validate()">
<table border="0">
<tr>
<td colspan="2">
<h1 class="title">Password Change Form</h1>
</td>
</tr>
<tr>
<td><span class="style20">Username </span></td>
<td><input name="username" id="username" type="text"></td>
<td><span id="usernameerror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Old Password</span></td>
<td><input name="pass" id="pass" type="password"></td>
<td><span id="pwderror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">New Password</span></td>
<td><input name="pass1" id="pass1" type="password"></td>
<td><span id="pwd1error" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Repeat New Password</span></td>
<td><input name="pass2" id="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>

Related

How to pass a text box value from one html page to another

I would like to pass a textbox value from one html page to another html page and print on the second page. I have page1.html and page2.html. I dont want to use asp or php any server side scripting language simply i want to do using javascript or jquery anyone which is easy.
<script>
function checkPassword() {
if (document.getElementById("name").value == "") {
document.getElementById("studname").innerHTML = "Enter your name. Field cannot be left blank.";
alert('Enter your name.');
return false;
}
else if (document.getElementById("class").value == "select") {
document.getElementById("classname").innerHTML = "Select your class.";
alert('Select your class.');
return false;
}
else if (document.getElementById("section").value == "select") {
document.getElementById("secname").innerHTML = "Select your section.";
alert('Select your section.');
return false;
}
else if (document.getElementById("password").value == "") {
document.getElementById("passwordname").innerHTML = "Enter your password.";
alert('Enter your password.');
return false;
}
else if (document.getElementById('password').value == '12345' && document.getElementById("class").value == 'V' && document.getElementById("section").value == 'a') {
location.href = 'Start.html?name=' + document.getElementById('name').value + '?class=' + document.getElementById('class').value;
}
else {
alert('Your Class, Section and Password doesn\'t match. Please re-enter correctly.');
return false;
}
}
</script>
Run this code, u ll get the output what u needed.
html1.html
<html>
<form type=get action="html2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</html>
html2.html
<html>
<script LANGUAGE="JavaScript">
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</html>

remove node from xml and save it using Javascript or Jquery

I have tried the last post example which works fine with IE from this link
How to write data from Form in HTML to XML with Javascript
but i would like to add a button 'delete' to remove each time a node of xml
using Javascript or Jquery. These examples don't work for me.
http://www.w3schools.com/xml/met_element_removechild.asp. Any one can help?
<!DOCTYPE html>
<html>
<head>
<title>Display Emp Details</title>
<script type="text/javascript" language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME='D:\\example.xml';
function SaveXMLData()
{
validations();
}
function createfile()
{
var file;
var e1=document.getElementById('empName').value;
var p1=document.getElementById('empNumber').value;
var em1=document.getElementById('empEmail').value;
var d1=document.getElementById('empDate').value;
var tablemain = document.getElementById('tblmain');
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var lng;
lng=xmlDoc.getElementsByTagName("Details");
var xmlread= fso.OpenTextFile(FILENAME,1,true,0);
var x=xmlread.readAll();
var replace=x.replace('</Emp>','');
var sno=lng.length + 1;
file=fso.OpenTextFile(FILENAME,2,true);
file.writeLine(replace);
file.WriteLine('<Details category="'+sno+'">');
file.WriteLine('<SNo>'+sno+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('another file updated');
}
else
{
file= fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
file.WriteLine('<Emp>');
file.WriteLine('<Details category="1">');
file.WriteLine('<SNo>'+1+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('file updated');
}
<!-- displayData();-->
document.getElementById('empName').value='';
document.getElementById('empNumber').value='';
document.getElementById('empEmail').value='';
document.getElementById('empDate').value='';
addRow('tablemain');
file.close();
}
function validations()
{
var emp1=document.getElementById('empName').value;
var letters = /^[\s A-Za-z]+$/;
if(emp1!="")
{
if(emp1.match(letters))
{
allnumeric();
}
else
{
alert('Please input alphabet characters only');
return false;
}
}
else
{
alert('Please Enter Name.');
}
}
<!--For checking Email-->
function checkemail()
{
var email = document.getElementById('empEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.value!="")
{
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
return false;
}
else
{
DateValidation();
}
}
else
{
alert('Please Enter Email.');
}
}
<!--For checking Date Format-->
function DateValidation()
{
var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
var empDate=document.getElementById("empDate");
if(empDate.value!="")
{
if(empDate.value.match(date))
{
createfile();
}
else
{
alert("Please provide valid date : DD-MM-YY(YYYY)");
return(false);
}
}
else
{
alert('Please Enter Date.');
}
}
<!--For checking phone number-->
function allnumeric()
{
var numbers=/^\d{10}$/;
var empNumber=document.getElementById("empNumber");
if(empNumber.value!="")
{
if(empNumber.value.length=="10")
{
if(empNumber.value.match(numbers))
{
checkemail();
}
else
{
alert("Phone number should be numeric");
return(false);
}
}
else
{
alert('Phone Number should be like: 9876543210');
}
}
else
{
alert('Please Enter Phone Number.');
}
}
function addRow(id)
{
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var x;
x=xmlDoc.getElementsByTagName("Details");
var table = document.getElementById('tbl');
var nxtbtn= document.getElementById("btnnext");
var prvbtn=document.getElementById("btnprev");
nxtbtn.disabled=true;
prvbtn.disabled=true;
if(x.length >5)
{
nxtbtn.disabled=false;
}
var j=0;k=5;
if(k>x.length)
{k=x.length;}
var store=document.getElementById("txtstore");
var maxval=document.getElementById("txtmax");
if(id=="btnprev")
{
if((store.value % k)==0)
{
store.value = store.value - k ;
if(store.value>0)
{
j = parseInt(store.value);
k += parseInt(store.value);
}
}
else
{
store.value =store.value - (store.value % k) ;
if(store.value >0)
{
j = store.value - k;
k = store.value;
}
}
if(j > 0)
{
prvbtn.disabled=false;
}
}
if(id=="btnnext")
{
if(store.value==0)
{
store.value=table.rows.length;
}
else if(store.value <0)
{
store.value=maxval.value;
}
prvbtn.disabled=false;
if(store.value >=k)
{
j +=parseInt(store.value);
k +=parseInt(store.value);
if(k >= x.length)
{
k=x.length;
nxtbtn.disabled = true;
prvbtn.disabled = false;
}
}
}
table.innerHTML = "";
var rowCount = 0;
for (i=j;i<k;i++)
{
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.id = "id2" ;
cell1.appendChild(element1);
// Create label
var label = document.createElement("label");
label.htmlFor = "id2" ;
cell1.appendChild(label);
var cell2 = row.insertCell(1);
cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
var name = row.insertCell(2);
var elname =document.createElement("input");
elname.type = "text";
elname.readOnly=true;
elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
name.appendChild(elname);
var phnno = row.insertCell(3);
var elphn =document.createElement("input");
elphn.type = "text";
elphn.readOnly=true;
elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
phnno.appendChild(elphn);
var email = row.insertCell(4);
var elemail =document.createElement("input");
elemail.type = "text";
elemail.readOnly=true;
elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
email.appendChild(elemail);
var date = row.insertCell(5);
var eldate =document.createElement("input");
eldate.type = "text";
eldate.readOnly=true;
eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
date.appendChild(eldate);
rowCount +=1;
}
maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
if(id=="btnprev")
{
store.value =store.value - 5;
}
else
{
store.value =parseInt(k);
}
}
}
</script>
</head>
<body onload="addRow('tbl')">
<form id="empForm" action="" method="get">
<p><b>Emp Registration:</b></p>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="empName" maxlength="25"/></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" id="empNumber" maxlength="10"/></td>
</tr>
<tr>
<td>EmailId:</td>
<td><input type="text" id="empEmail"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" id="empDate" maxlength="10"/></td>
</tr>
<tr>
<td align="center">
<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
<td>
<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
</tr>
</table>
<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
<td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->
<div id='displaydatadiv'>
</div>
<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
<div style="height: 135px; width:650px; background-color: Lavender;" >
<TABLE id="tbl" width="350px">
</TABLE>
</div>
<table id="tblmain" border="1" style="display:true" ></table>
<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">
<input type="hidden" id="txtstore" style="display:none;">
<input type="hidden" id="txtmax" style="display:none;">
</body>
</html>

Test if radio and checkbox button are checked

I want to know if my radio button and checkbox are checked. If so I will save the change in the database.
Here is my form code :
<SCRIPT>
function set(target) {
var val1;
if (target == 'save') {
val1 = getradiovalue('officialForCalculation');
document.forms[1].selectedOfficialCalc.value = val1;
}
document.forms[1].button.value= target;
document.forms[1].submit();
}
function getradiovalue(rad) {
var rad_val;
if (rad == 'officialForCalculation')
if (document.forms[1].officialCalculation) {
if (!document.forms[1].officialCalculation[1]) {
if (document.forms[1].officialCalculation.checked) {
rad_val = document.forms[1].officialCalculation.value;
}
} else {
for (var i = 1; i < document.forms[1].officialCalculation.length; i++) {
if (document.forms[1].officialCalculation[i].checked) {
rad_val = document.forms[1].officialCalculation[i].value;
}
}
}
}
return rad_val;
}
</SCRIPT>
<form action="/getAll.do" name="table">
<logic:present name="frmTransitionMatrix" property="matrixes">
<logic:iterate name="frmTransitionMatrix" property="matrixes" id="matrixid">
<c:if test="${matrixid.officialForCalculation=='1'}">
<td align="center" width="25%"><input type="radio"
name="officialForCalculation"
value="<bean:write
name="matrixid" property="idTransitionMatrix"/>" checked='checked'/>
</td>
</c:if>
<c:if test="${matrixid.officialForCalculation=='0'}">
<td align="center" width="25%"><input type="radio"
name="officialForCalculation"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"/>
</td>
</c:if>
<logic:equal value="1" name="matrixid" property="active">
<td align="center" width="25%"><input type="checkbox"
name="activeMatrix"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"
checked /></td>
</logic:equal>
<logic:equal value="0" name="matrixid" property="active">
<td align="center" width="25%"><input type="checkbox"
name="activeMatrix"
value="<bean:write name="matrixid" property="idTransitionMatrix"/>"/>
</td>
</logic:equal>
</tr>
</logic:iterate>
</logic:present>
<input type="button" name="button" value="Save" class="button" onClick="set('save');"/>
</form>
Here is my MatrixForm
#Data
public class MatrixForm extends ActionForm {
private List<MatrixEntity> matrixes = new ArrayList<MatrixEntity>();
private String allMatrixes;
private String selectedOfficialCalc;
private String[] activeMatrix;
}
My Action class
public ActionForward updateAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws DBAccessException, TimeOutException {
MatrixForm faForm = (MatrixForm) form;
MatrixDaoImpl matrixDao = new MatrixDaoImpl();
String MatrixForCalc = faForm.getSelectedOfficialCalc();
List<String> validForCalcList = new ArrayList<String>();
validForCalcList.add(MatrixForCalc);
String[] activeMatrix = faForm.getActiveMatrix();
List<String> actMatrixsList = new ArrayList<String>();
if (activeMatrix != null) {
for (int i = 0; i < activeMatrix.length; i++) {
actMatrixsList.add(activeMatrix[i]);
}
}
List<MatrixEntity> matrixes = faForm.getMatrixes();
MatrixEntity Entity;
if (matrixes != null && !matrixes.isEmpty()) {
for (MatrixEntity matrix : matrixes) {
if (validForCalcList != null && !validForCalcList.isEmpty()
&& validForCalcList.contains(matrix.getIdTransitionMatrix())) {
if (!actMatrixsList.contains(matrix.getIdTransitionMatrix())) {
//getB2SContext(request).setErrorInfo("The Official Portfolio for Calculation cannot be inactive");
return mapping.findForward("active");
}
}
}
for (int count = 0; count < matrixes.size(); count++) {
Entity = matrixes.get(count);
if (validForCalcList != null && !validForCalcList.isEmpty()
&& validForCalcList.contains(Entity.getIdTransitionMatrix())) {
if (!actMatrixsList.contains(Entity.getIdTransitionMatrix())) {
//getB2SContext(request).setErrorInfo("The Official Portfolio for Calculation cannot be inactive");
return mapping.findForward("active");
} else {
Entity.setActive(BigInteger.ONE);
Entity.setOfficialForCalculation(BigInteger.ONE);
}
} else {
if (actMatrixsList.contains(Entity.getIdTransitionMatrix())) {
Entity.setActive(BigInteger.ONE);
} else {
Entity.setActive(BigInteger.ZERO);
}
Entity.setOfficialForCalculation(BigInteger.ZERO);
}
}
matrixDao.updateAll(matrixes);
}
I have debugged my code and I've found that activeMatrix is null even if it's checked and the same thing occurs for selectedOfficialCalc. I want to know how I can set the properties of my MatrixForm if they are checked.

Javascript / RegEx not validating HTML form

The issue is that it appears that non of my JavaScript is working and I've spent hours trying to figure out why, I can't find any obvious errors and I'm fairly new to JavaScript in general, but i'm trying to get JavaScript to validate the code in my form together with regEx and as of right now its not doing anything.
Heres the code for my Form:
<form action="ValideringVM.php" method="post" name="Registrer" onsubmit="return valider_alle()">
<table>
<tr>
<td><h3> Personalia:</h3> </td>
</tr>
<tr>
<td> Fornavn: </td>
<td><input type="text" name="Fornavn" onChange="valider_fornavn()"/></td>
<td><div id="FeilFornavn">*</div></td>
</tr>
<tr>
<td> Etternavn: </td>
<td><input type="text" name="Etternavn" onChange="valider_etternavn()"/></td>
<td><div id="FeilEtternavn">*</div></td>
</tr>
<tr>
<td> Adresse: </td>
<td><input type="text" name="Adresse" onChange="valider_adresse()"/></td>
<td><div id="FeilAdresse">*</div></td>
</tr>
<tr>
<td> Postnr: </td>
<td><input type="text" name="Postnr" onChange="valider_postnr()"/></td>
<td><div id="FeilPostnr">*</div></td>
</tr>
<tr>
<td> Email: </td>
<td><input type="text" name="Email" onChange="valider_email()"/></td>
<td><div id="FeilEmail">*</div></td>
</tr>
<tr>
<td> Telefonnr: </td>
<td><input type="text" name="Telefonnr" onChange="valider_telefonnr()"/></td>
<td><div id="FeilTelefonnr">*</div></td>
</tr>
<tr>
<td> Lag Brukernavn: </td>
<td><input type="text" name="Brukernavn" onChange="valider_brukernavn()"/></td>
<td><div id="Feilbruker">*</div></td>
</tr>
<tr>
<td> Lag Passord: </td>
<td><input type="password" name="Passord" onChange="valider_passord()"/></td>
<td><div id="Feilpassord">*</div></td>
</tr>
<tr>
<td><input type="submit" name="Send" value="Send"/></td>
</tr>
</table>
</form>
and heres my Javascript code:
<script type="text/javascript">
function valider_fornavn()
{
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;
OK = regEx.test(document.Registrer.Fornavn.value);
if(!OK)
{
document.getElementById("FeilFornavn").innerHTML="Feil i Fornavn";
return false;
}
document.getElementById("FeilFornavn").innerHTML="";
return true;
}
function valider_etternavn()
{
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;
OK = regEx.test(document.Registrer.Etternavn.value);
if(!OK)
{
document.getElementById("FeilEtternavn").innerHTML="Feil i Etternavn";
return false;
}
document.getElementById("FeilEtternavn").innerHTML="";
return true;
}
function valider_adresse()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9.\- ](2,30)$/;
OK = regEx.test(document.Registrer.Adresse.value);
if(!OK)
{
document.getElementById("FeilAdresse").innerHTML="Feil i Adresse";
return false;
}
document.getElementById("FeilAdresse").innerHTML="";
return true;
}
function valider_postnr()
{
regEx = /^[0-9](4)$/;
OK = regEx.test(document.Registrer.Postnr.value);
if(!OK)
{
document.getElementById("FeilPostnr").innerHTML="Feil i Postnr";
return false;
}
document.getElementById("FeilPostnr").innerHTML="";
return true;
}
function valider_email()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9._%+-]+#[a-zA-ZæøåÆØÅ 0-9.-]+\.[a-z]{2,4}$/;
OK = regEx.test(document.Registrer.Email.value);
if(!OK)
{
document.getElementById("FeilEmail").innerHTML="Feil i Email";
return false;
}
document.getElementById("FeilEmail").innerHTML="";
return true;
}
function valider_telefonnr()
{
regEx = /^[0-9]{8}$/;
OK = regEx.test(document.Registrer.Telefonnr.value);
if(!OK)
{
document.getElementById("FeilTelefonnr").innerHTML="Feil i Telefonnummer";
return false;
}
document.getElementById("FeilTelefonnr").innerHTML="";
return true;
}
function valider_brukernavn()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9](4,20)$/;
OK = regEx.test(document.Registrer.Brukernavn.value);
if(!OK)
{
document.getElementById("Feilbruker").innerHTML="Feil i brukernavnet";
return false;
}
document.getElementById("FeilBruker").innerHTML="";
return true;
}
function valider_passord()
{
regEx = /^[a-zA-ZæøåÆØÅ 0-9](4,20)$/;
OK = regEx.test(document.Registrer.Passord.value);
if(!OK)
{
document.getElementById("FeilPassord").innerHTML="Feil i passordet";
return false;
}
document.getElementById("FeilPassord").innerHTML="";
return true;
}
function valider_alle()
{
(e || window.event).preventDefault();
FornavnOK = valider_fornavn();
EtternavnOK = valider_etternavn();
AdresseOK = valider_adresse();
PostnrOK = valider_postnr();
TelefonnrOK = valider_telefonnr();
EmailOK = valider_email();
BrukernavnOK = valider_brukernavn();
PassordOK = valider_passord();
}
if(FornavnOK && EtternavnOK && AdresseOK && PostnrOK && TelefonnrOK && EmailOK && BrukernavnOK && PassordOK)
{
return true;
}
else
{
return false;
}
</script>
last function valider_alle end brace is not set to its right place
function valider_alle()
{
(e || window.event).preventDefault();
FornavnOK = valider_fornavn();
EtternavnOK = valider_etternavn();
AdresseOK = valider_adresse();
PostnrOK = valider_postnr();
TelefonnrOK = valider_telefonnr();
EmailOK = valider_email();
BrukernavnOK = valider_brukernavn();
PassordOK = valider_passord();
//} this one must be at the end
if(FornavnOK && EtternavnOK && AdresseOK && PostnrOK && TelefonnrOK && EmailOK && BrukernavnOK && PassordOK)
{
return true;
}
else
{
return false;
}
}
and if you are ensuring that the length is between 2 and 20 like that:
regEx = /^[a-zA-ZæøåÆØÅ .\- ](2,20)$/;// ( and ) is not for length
it must be written:
regEx = /^[a-zA-ZæøåÆØÅ .\- ]{2,20}$/;

What is wrong with my code?

I'm having trouble with my code but can't seem to find what the problem is. I keep getting the same errors in browser but I don't see what the problem is?
FVOM.js:16 Uncaught SyntaxError: Unexpected number
FVOM.html:15 Uncaught ReferenceError: CheckSelection is not defined
HTML code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Demo</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<script type="text/javascript" src="JScripts/FVOM.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<input type="radio" id="futVal" name="Money" checked onClick="FVOM:CheckSelection(1)"/>Future Value
<input type="radio" id="preVal" name="Money" onClick="FVOM:CheckSelection(2)"/>Present Value
<input type="radio" id="rate" name="Money" onClick="FVOM:CheckSelection(3)"/>Rate of Interest
<input type="radio" id="time" name="Money" onClick="FVOM:CheckSelection(4)"/>Years
</td>
</tr>
</table>
<br/>
<table>
<tr>
<td>Future Value (FV)</td>
<td><input type="text" id="FV" disabled/></td>
</tr>
<tr>
<td>Present Value (PV)</td>
<td><input type="text" id="PV" value = "1500" /></td>
</tr>
<tr>
<td>Interest Rate [pa] (r)</td>
<td><input type="text" id="R" value = "4.5"/></td>
</tr>
<tr>
<td>Years (n)</td>
<td><input type="text" id="N" value = "1"/></td>
</tr>
<tr>
<td>Compounded</td>
<td>
<select id="compounded">
<option value="year">Yearly</option>
<option value="quarter">Quarterly</option>
<option value="month">Monthly</option>
</select>
</td>
</tr>
<tr>
<td><input type="button" id="reset" value="RESET"/></td>
<td><input type="button" id="calculate" value="Calculate"/></td>
</tr>
</table>
<br/>
<hr/>
<br/>
<div id="results">
</div>
</body>
JavaScript:
var $ = function(id){
return document.getElementById(id);
};
var futureValue = function(){
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(pv) || isNaN(r) || isNaN(n)){
alert("Please enter a valid number");
}
else{
r = r/100/Compounded();
n = n*Compounded();
$("FV").value=(pv*Math.pow((1+r), n)).toFixed(2);
var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
for(var i=1; i<=n; i++){
res+="<tr><td>"+i+"</td><td>€"+(pv).toFixed(2)+"</td><td>€"+(pv*Math.pow((1+r), 1)).toFixed(2)+"</td></tr>";
pv = pv*Math.pow((1+r), 1);
}
res+="</table>";
$("results").innerHTML = res;
}
};
var presentValue = function(){
var fv = parseFloat($("FV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(r) || isNaN(n))
alert("Please enter numbers");
else{
r = r/100/Compounded();
n = n*Compounded();
$("PV").value=(fv/Math.pow((1+r), n)).toFixed(2);
}
};
var rateOfInterest = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(pv) || isNaN(n))
alert("Please enter numbers");
else{
n = n*Compounded();
$("R").value=((Math.pow((fv/pv),(1/n))-1)*100*Compounded()).toFixed(2)+"%";
}
};
var numberOfYears = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
if(isNaN(fv) || isNaN(pv) || isNaN(r))
alert("Please enter numbers");
else{
r = r/100/Compounded;
$("N").value=(((Math.log(fv)-Math.log(pv))/Math.log(1 + r)))n/Compounded()).toFixed(2);
}
};
var Compounded = function(){
var com = $("compounded").value;
if(com=="year")
return 1;
if(com=="quarter")
return 4;
if(com=="month")
return 12;
};
var calculate = function(){
if($("futVal").checked)
futureValue();
if($("preVal").checked)
presentValue();
if($("rate").checked)
rateOfInterest();
if($("time").checked()
numberOfYears();
};
var CheckSelection = function(id){
if(id==1){
$("FV").disabled = true;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==2){
$("FV").disabled = false;
$("PV").disabled = true;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==3){
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = true;
$("N").disabled = false;
}
else{
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = true;
}
RESET();
};
var RESET = function(){
$("FV").value = "";
$("PV").value = "";
$("R").value = "";
$("N").value = "";
$("results").innerHTML = "";
};
window.onload = function(){
$("calculate").onClick = calculate;
$("reset").onClick = RESET;
};
I'm fairly new to JavaScript so any help would be greatly appreciated.
var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
is where the problem lies. You need to escape the " (double quotes) that exist in border="1" by either using a \" or by using single quotes '
For this reason some people use single quotes in javascript to assign a string, that way you do not need to escape the double quotes. If you would like to read more about strings in javascript there is a decent introduction at http://www.w3schools.com/js/js_strings.asp

Categories