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}$/;
Related
I am creating a web form that contains a table housing radio buttons as options for the user to pick. I have grouped the rows by ID and wish the page to not allow users to continue unless each row has a valid selection. I am having trouble with this as the form posts as long as one group has a selection and doesn't assess all the groups. I have included 2 groups for testing purposes, but my webform will actually contain more. I am very new to C# and JavaScript, but I know that I have an issue that both are using isChecked, but I am sure this is not the only issue. I have used this as a guide https://www.codemahal.com/video/radio-buttons-and-form-validation/
Here is my code
<script type="text/javascript">
function isChecked() {
var checkedITEx = document.getElementById('IT-Ex').checked;
var checkedITVG = document.getElementById('IT-VG').checked;
var checkedITGd = document.getElementById('IT-Gd').checked;
var checkedITAve = document.getElementById('IT-Ave').checked;
var checkedITPoor = document.getElementById('IT-Poor').checked;
if (checkedITEx == false && checkedITVG == false && checkedITGd == false && checkedITAve == false && checkedITPoor == false) {
alert('You need to select a rating for Independent Thinking');
return false;
}
else {
return true;
}
}
function isChecked() {
var checkedResEx = document.getElementById('Res-Ex').checked;
var checkedResVG = document.getElementById('Res-VG').checked;
var checkedResGd = document.getElementById('Res-Gd').checked;
var checkedResAve = document.getElementById('Res-Ave').checked;
var checkedResPoor = document.getElementById('Res-Poor').checked;
if (checkedResEx == false && checkedResVG == false && checkedResGd == false && checkedResAve == false && checkedResPoor == false) {
alert('You need to select a rating for Resiliance');
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server" action="Default.aspx" method="get" onsubmit="return isChecked();">
<table>
<tr>
<td class="auto-style1"></td>
<td class="auto-style2">Excellent</td>
<td class="auto-style2">Very Good</td>
<td class="auto-style2">Good</td>
<td class="auto-style2">Average</td>
<td class="auto-style2">Poor</td>
</tr>
<tr>
<td class="auto-style1">Independent Thinking</td>
<td class="auto-style2"><input type="radio" name="IndThink" value ="Independent Thinking - Excellent" id="IT-Ex"/></td>
<td class="auto-style2"><input type="radio" name="IndThink" value ="Independent Thinking - Very Good" id="IT-VG"/></td>
<td class="auto-style2"><input type="radio" name="IndThink" value ="Independent Thinking - Good" id="IT-Gd"/></td>
<td class="auto-style2"><input type="radio" name="IndThink" value ="Independent Thinking - Average" id="IT-Ave"/></td>
<td class="auto-style2"><input type="radio" name="IndThink" value ="Independent Thinking - Poor" id="IT-Poor"/></td>
</tr>
<tr>
<td class="auto-style1">Resiliance</td>
<td class="auto-style2"><input type="radio" name="Res" value ="Resiliance - Excellent" id="Res-Ex"/></td>
<td class="auto-style2"><input type="radio" name="Res" value ="Resiliance - Very Good" id="Res-VG"/></td>
<td class="auto-style2"><input type="radio" name="Res" value ="Resiliance - Good" id="Res-Gd"/></td>
<td class="auto-style2"><input type="radio" name="Res" value ="Resiliance - Average" id="Res-Ave"/></td>
<td class="auto-style2"><input type="radio" name="Res" value ="Resiliance - Poor" id="Res-Poor"/></td>
</tr>
</table>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
function isOneChecked() {
var checkedResEx = document.getElementById('Res-Ex').checked;
var checkedResVG = document.getElementById('Res-VG').checked;
var checkedResGd = document.getElementById('Res-Gd').checked;
var checkedResAve = document.getElementById('Res-Ave').checked;
var checkedResPoor = document.getElementById('Res-Poor').checked;
return (checkedResEx || checkedResVG || checkedResGd || checkedResAve || checkedResPoor);
}
This will return true if at least one of the checkboxes is checked.
I have manged to get this to co-operate. Here is the code I eventually went with:
<script type="text/javascript">
function isChecked()
{
var checkedITEx = document.getElementById('IT-Ex').checked;
var checkedITVG = document.getElementById('IT-VG').checked;
var checkedITGd = document.getElementById('IT-Gd').checked;
var checkedITAve = document.getElementById('IT-Ave').checked;
var checkedITPoor = document.getElementById('IT-Poor').checked;
if (checkedITEx == false && checkedITVG == false && checkedITGd == false && checkedITAve == false && checkedITPoor == false)
{
alert('You need to select a rating for Independent Thinking');
return false;
}
else
{
var checkedResEx = document.getElementById('Res-Ex').checked;
var checkedResVG = document.getElementById('Res-VG').checked;
var checkedResGd = document.getElementById('Res-Gd').checked;
var checkedResAve = document.getElementById('Res-Ave').checked;
var checkedResPoor = document.getElementById('Res-Poor').checked;
if (checkedResEx == false && checkedResVG == false && checkedResGd == false && checkedResAve == false && checkedResPoor == false)
{
alert('You need to select a rating for Resiliance');
return false;
}
else
{
return true;
}
}
}
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>
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.
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
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>