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>
Related
I made a code for my website with session and local storage. Though it seems it's not working and i don't know what is the problem. I tried everything to make it work but i can't. The problem is that you can register the local and session storage can save your details but i can't do the login. The login button is always disabled.
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="logreg.js"></script>
</head>
<body>
<script>
document.write(outstate(isative()));
</script>
<form>
<input type="email" id="user" onblur="verlogin()" required>
<input type="password" id="pass" onblur="verlogin()" required>
<span id="mess"></span>
<button type="submit" disabled id="login" onclick="login();">LOGIN</button>
</form>
<input type="email" id="usermail" onblur="veruser();ch();" required>
<span id="veruser"></span>
<button style="text-decoration: none!important;display: none;" id="uservalue" value="0"></button>
<input type="password" id="password" onblur="verpass();ch();" required>
<input type="password" id="confirmpassword" onblur="verpass();ch();" required>
<span id="verpass"></span>
<button style="text-decoration: none!important;display: none;" id="passvalue" value="0"></button>
<input type="text" id="morada" required>
<input type="number" maxlength="9" id="nif" required>
<button type="submit" id="registar" onclick="registar();">REGISTER</button>
</body>
</html>
JAVASCRIPT CODE:
window.onload=function(){
if(sessionStorage.length==0){
var key='';
for(var i=0;i<localStorage.length;i++){
key = localStorage.key(i);
sessionStorage.setItem(key,'');
}
}
}
function verlogin(){
var nome=document.getElementById('user').value;
var pass=document.getElementById('pass').value;
document.getElementById('mess').innerHTML = '';
var key='';
var val='';
if(localStorage.length!=0){
for(var i=0;i<localStorage.length;i++){
key = localStorage.key(i);
val = localStorage.getItem(key);
if(nome!='' || pass!=''){
if(nome==key){
if(val.substr(0, val.indexOf('|'))==pass) {
document.getElementById('mess').style.color='green';
document.getElementById('mess').innerHTML = 'VALID';
document.getElementById("login").disabled = false;
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'User or Wrong Password';
}
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'User or Wrong Password';
}
}else{
document.getElementById('mess').innerHTML = '';
}
}
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'Create an Account';
}
}
function login(){
var nome=document.getElementById('user').value;
sessionStorage.setItem(nome,'ativo');
window.location.href='index.html';
}
function veruser(){
var nome=document.getElementById('usermail').value;
document.getElementById('uservalue').value = 0;
var key='';
if(localStorage.length!=0) {
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
if (nome != '') {
if (nome == key) {
document.getElementById('uservalue').value = 0;
document.getElementById('veruser').style.color = 'red';
document.getElementById('veruser').innerHTML = 'User already in use';
} else {
document.getElementById('uservalue').value = 1;
document.getElementById('veruser').style.color = 'green';
document.getElementById('veruser').innerHTML = 'Valid';
}
} else {
document.getElementById('veruser').innerHTML = '';
}
}
}else{
document.getElementById('uservalue').value = 1;
document.getElementById('veruser').style.color = 'green';
document.getElementById('veruser').innerHTML = 'Valid';
}
}
function ch(){
var verp = document.getElementById('passvalue').value;
var veru = document.getElementById('uservalue').value;
document.getElementById("login").disabled = true;
if(verp==1 && veru==1){
document.getElementById("registar").disabled = false;
}else{
document.getElementById("login").disabled = true;
}
}
function verpass(){
var pass1=document.getElementById('password').value;
var pass2=document.getElementById('confirmpassword').value;
document.getElementById('passvalue').value = 0;
if(pass1!='' || pass2!=''){
if(pass1!=pass2){
document.getElementById('passvalue').value = 0;
document.getElementById('verpass').style.color='red';
document.getElementById('verpass').innerHTML = 'Passwords don't match';
}else{
document.getElementById('passvalue').value = 1;
document.getElementById('verpass').style.color='green';
document.getElementById('verpass').innerHTML = 'Valid';
}
}else{
document.getElementById('veruser').innerHTML = '';
}
}
function registar(){
var verp = document.getElementById('passvalue').value;
var veru = document.getElementById('uservalue').value;
var user=document.getElementById('usermail').value;
var pass=document.getElementById('password').value;
var mor=document.getElementById('morada').value;
var nif=document.getElementById('nif').value;
if(verp=='1' && veru=='1'){
localStorage.setItem(user,pass + '|'+mor);
sessionStorage.setItem(user,'ativo');
window.location.href='index.html';
}else{
alert('ERRO');
}
}
function logout(){
var key='';
var val='';
for(var i=0;i<sessionStorage.length;i++){
key = sessionStorage.key(i);
val = sessionStorage.getItem(key);
if(val=='ativo'){
sessionStorage.setItem(key,'');
window.location.href='index.html';
}
}
}
function isative(){
var key='';
var val='';
var user='';
for(var i=0;i<sessionStorage.length;i++){
key = sessionStorage.key(i);
val = sessionStorage.getItem(key);
if(val=='ativo'){
user = key;
}else{
user=0;
}
}
return user;
}
function outstate(ative){
var content='';
if(ative!=0){
alert(ative);
content+= '<h6>The user ' + ative+' is online<h6>';
content +='<button type="submit" onclick="logout();">LOGOUT</button>'
}else{
content +='<h6>Not Connected<h6>';
}
return content
}
I don't know what to do anymore... :(
If I give semicolon as input means I have to create a textbox in jQuery. I tried this code and it flows correctly but it didn't show me the result.
$(document).ready(function (){
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 59)
{
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
alert("friends");
addbox();
}
}
});
});
addbox code is here
function addbox() {
var table = $(this).closest('table');
if (table.find('input:text').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
My ASp.Net Markup is
<asp:TextBox ID="hellotxt" runat="server" placeholder="hi;ji;ki;li;"> </asp:TextBox>
<table border="0" cellspacing="2">
<tr>
<td>
<input type="button" id="add" value="Add" />
<input type="button" id="del" value="Del" />
</td>
</tr>
you will get answer from this code..please you all guys check it out
$(document).ready(function (){
//page load
$("#hellotxt").on('keypress', function (event) {
console.log(event.which)
if (event.which == 59 || event.which == 186) {
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox.call(this, valueSortArray);
}
}
});
function addbox(valueSortArray) {
var table = $(this).next('table').find("tbody");
table.find(".dyn").remove()
$.each(valueSortArray, function (i, v) {
console.log(i,v)
if (v)
table.append('<tr class="dyn"><td><input type="text" value="' + v + '" /></td></tr> ');
})
check below code keycode for ';' is 186 . check working example on fiddle
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 186)
{
var OBJ = $(this);
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox(OBJ);
}
}
});
pass $(this)(hellotxt object) as argument in function
function addbox( OBJ ) {
var table = OBJ.next('table');
if (table.find('input').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
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>
I have a editable gridview. When I click on edit button corresponding to a row in the gridview I provide two textboxes to enter two new values.2 textboxes as I have 2 columns. Now this textbox are generated at runtime.I want to access this textbox in javascript and perform validation on them.This is the html syntax.
<table cellspacing="0" rules="all" border="1" id="TableGridView" style="border-collapse:collapse;table-layout:fixed">
<tr>
<th scope="col"><b>Action</b></th><th scope="col"><b>PROCESSOR_ID</b></th><th scope="col"><b>PROCESSOR_NAME</b></th>
</tr><tr>
<td><input type="image" name="TableGridView$ctl02$edit_button" id="TableGridView_ctl02_edit_button" title="Edit" src="images/edit.gif" style="border-width:0px;" /><input type="image" name="TableGridView$ctl02$delete_button" id="TableGridView_ctl02_delete_button" title="Delete" src="images/delete.gif" onclick="return confirm('Are you sure you want to delete the record?');" style="border-width:0px;" /><input type="image" name="TableGridView$ctl02$insert_button" id="TableGridView_ctl02_insert_button" title="Insert" src="images/insert.bmp" style="border-width:0px;" /></td><td><span id="TableGridView_ctl02_PROCESSOR_ID">23</span></td><td><span id="TableGridView_ctl02_PROCESSOR_NAME">dasdas</span></td>
</tr><tr>
<td><input type="image" name="TableGridView$ctl03$edit_button" id="TableGridView_ctl03_edit_button" title="Edit" src="images/edit.gif" style="border-width:0px;" /><input type="image" name="TableGridView$ctl03$delete_button" id="TableGridView_ctl03_delete_button" title="Delete" src="images/delete.gif" onclick="return confirm('Are you sure you want to delete the record?');" style="border-width:0px;" /><input type="image" name="TableGridView$ctl03$insert_button" id="TableGridView_ctl03_insert_button" title="Insert" src="images/insert.bmp" style="border-width:0px;" /></td><td><span id="TableGridView_ctl03_PROCESSOR_ID">123</span></td><td><span id="TableGridView_ctl03_PROCESSOR_NAME">asdasdas</span></td>
</tr><tr>
<td><input type="image" name="TableGridView$ctl04$update_button" id="TableGridView_ctl04_update_button" title="Add" src="images/update.gif" onclick="return (textfieldvalidation());" style="border-width:0px;" /><input type="image" name="TableGridView$ctl04$cancel_button" id="TableGridView_ctl04_cancel_button" title="Cancel" src="images/cancel.gif" style="border-width:0px;" /></td><td><input name="TableGridView$ctl04$PROCESSOR_ID" type="text" id="TableGridView_ctl04_PROCESSOR_ID" /></td><td><input name="TableGridView$ctl04$PROCESSOR_NAME" type="text" id="TableGridView_ctl04_PROCESSOR_NAME" /></td>
</tr><tr>
<td><input type="image" name="TableGridView$ctl05$edit_button" id="TableGridView_ctl05_edit_button" title="Edit" src="images/edit.gif" style="border-width:0px;" /><input type="image" name="TableGridView$ctl05$delete_button" id="TableGridView_ctl05_delete_button" title="Delete" src="images/delete.gif" onclick="return confirm('Are you sure you want to delete the record?');" style="border-width:0px;" /><input type="image" name="TableGridView$ctl05$insert_button" id="TableGridView_ctl05_insert_button" title="Insert" src="images/insert.bmp" style="border-width:0px;" /></td><td><span id="TableGridView_ctl05_PROCESSOR_ID">6456</span></td><td><span id="TableGridView_ctl05_PROCESSOR_NAME">dg</span></td>
</tr>
</table>
I 'have' to use IE 6.0.
I have already tried document.getElementbyID for the table and getElementsByTagName adn they are not working.
var curValue = document.getElementById("<%=TableGridView.ClientID%>").rows;
curValue is 1 in IE and 4 in firefox.
You should pass the reference of the clicked element and avoid playing with ID's.
<input type="image" ... onclick="return textfieldvalidation(this)"...
And the function
function textfieldvalidation(button){
var tr = button.parentNode.parentNode,
inputs = tr.getElementsByTagName('INPUT'), //all INPUT tags of the TR
id = inputs[0].getAttribute('id'); //or inputs[0].id
}
Here I am giving the Example how you will do that here the java script code
enter code here
// JScript File
//This method is used to add rows if email field is validated
function addRows(tableID)
{
if(validate(this.obj))
{
var emailTableRow = document.getElementById("ctl00_ContentPlaceHolder1_EmailTableRow").value;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var lastRow;
if (emailTableRow == '') {
emailTableRow = "'1'";
lastRow = 1;
}
else
{
lastRow = emailTableRow.substr(emailTableRow.lastIndexOf(",") + 2, emailTableRow.lastIndexOf("'") - (emailTableRow.lastIndexOf(",") + 2));
}
var newRow = parseInt(lastRow) + 1;
emailTableRow = emailTableRow + ",'" + newRow.toString() + "'";
document.getElementById("ctl00_ContentPlaceHolder1_EmailTableRow").value = emailTableRow;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
cell0.style.marginLeft="0px";
cell0.style.width="200px";
cell0.style.height="12px";
//cell0.style.line-height="12px";
cell0.style.paddingLeft="0px";
cell0.style.background="#70b9ee";
cell0.style.fontFamily="Trebuchet MS";
cell0.style.fontSize="11px";
cell0.style.fontWeight="normal";
cell0.style.color="#fff";
cell0.style.textAlign="center";
cell0.style.border="0px solid #000";
var element0 = document.createElement("label");
element0.innerHTML = newRow;
element0.setAttribute("size", "3");
element0.setAttribute("name", "lblRownumber" + newRow.toString());
element0.setAttribute("id", "lblRownumber" + newRow.toString());
cell0.appendChild(element0);
var cell1 = row.insertCell(1);
cell1.style.marginLeft="0px";
cell1.style.width="200px";
cell1.style.height="12px";
//cell0.style.line-height="12px";
cell1.style.paddingLeft="0px";
cell1.style.background="#70b9ee";
cell1.style.fontFamily="Trebuchet MS";
cell1.style.fontSize="11px";
cell1.style.fontWeight="normal";
cell1.style.color="#fff";
cell1.style.textAlign="center";
cell1.style.border="0px solid #000";
var element1 = document.createElement("input");
element1.type = "text";
element1.setAttribute("name", "txtEMAIL_ADDRESS" + newRow.toString());
element1.setAttribute("id", "txtEMAIL_ADDRESS"+ newRow.toString());
cell1.appendChild(element1);
var cell2 = row.insertCell(2);
cell2.style.marginLeft="0px";
cell2.style.width="200px";
cell2.style.height="12px";
//cell0.style.line-height="12px";
cell2.style.paddingLeft="0px";
cell2.style.background="#70b9ee";
cell2.style.fontFamily="Trebuchet MS";
cell2.style.fontSize="11px";
cell2.style.fontWeight="normal";
cell2.style.color="#fff";
cell2.style.textAlign="center";
cell2.style.border="0px solid #000";
var element2 = document.createElement("input");
element2.setAttribute("name", "txtName"+newRow.toString());
element2.setAttribute("id", "txtName"+newRow.toString());
element2.type = "text";
cell2.appendChild(element2);
var cell3 = row.insertCell(3);
cell3.style.marginLeft="0px";
cell3.style.width="200px";
cell3.style.height="12px";
//cell0.style.line-height="12px";
cell3.style.paddingLeft="0px";
cell3.style.background="#70b9ee";
cell3.style.fontFamily="Trebuchet MS";
cell3.style.fontSize="11px";
cell3.style.fontWeight="normal";
cell3.style.color="#fff";
cell3.style.textAlign="center";
cell3.style.border="0px solid #000";
var element3 = document.createElement("input");
element3.setAttribute("name", "txtPROMOTIONAL_COMPAIGN"+newRow.toString());
element3.setAttribute("id", "txtPROMOTIONAL_COMPAIGN"+newRow.toString());
element3.type = "text";
cell3.appendChild(element3);
var row = table.insertRow(rowCount+1);
var cell0 = row.insertCell(0);
cell0.colSpan = 4;
cell0.style.textAlign = "left";
cell0.style.paddingLeft = "0px"
cell0.style.fontWeight="normal";
cell0.style.fontSize="11px";
cell0.style.fontFamily="Trebuchet MS";
cell0.style.marginLeft="0px";
//cell0.style.margin="0px";
// cell0.style.width="200px";
// cell0.style.height="20px";
// cell0.style.line-height="12px";
cell0.style.paddingLeft="5px";
cell0.style.background="#70b9ee";
// cell0.style.font-family="Trebuchet MS";
// cell0.style.font-size="11px";
// cell0.style.font-weight="normal";
cell0.style.color="#fff";
// cell0.style.text-align="left";
//cell0.style.border="0px solid #000";
var element0 = document.createElement("label");
element0.innerHTML ="Please feel free to change the Text";
element0.setAttribute("size", "100");
element0.setAttribute("name", "lblMessage" + newRow.toString());
element0.setAttribute("id", "lblMessage" + newRow.toString());
element0.setAttribute("class","srn-td-space3");
cell0.appendChild(element0);
var row = table.insertRow(rowCount+2);
var cell0 = row.insertCell(0);
cell0.colSpan = 4;
cell0.style.textAlign = "left";
cell0.style.paddingLeft = "5px"
cell0.style.fontWeight="normal";
cell0.style.fontSize="11px";
cell0.style.fontFamily="Trebuchet MS";
cell0.style.marginLeft="1px";
// cell0.style.width="200px";
// cell0.style.height="20px";
// cell0.style.line-height="12px";
// cell0.style.paddingLeft="0px";
cell0.style.background="#70b9ee";
// cell0.style.font-family="Trebuchet MS";
// cell0.style.font-size="11px";
// cell0.style.font-weight="normal";
cell0.style.color="#fff";
// cell0.style.text-align="left";
//cell0.style.border="0px solid #000";
var element0 = document.createElement("textarea");
element0.setAttribute("cols", "50");
element0.setAttribute("rows", "4");
element0.setAttribute("name", "txtAreaEmailBody" + newRow.toString());
element0.setAttribute("id", "txtAreaEmailBody" + newRow.toString());
cell0.appendChild(element0);
}
return false;
}
//This method is used to Validate Email.....
function validate(formobj) {
var emailPattern = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var getWorkFields;
getWorkFields = getFieldRequired('ctl00_ContentPlaceHolder1_SendmailsTable', 'ctl00_ContentPlaceHolder1_EmailTableRow', 'txtEMAIL_ADDRESS');
var fRequired = getWorkFields;
var fieldRequired = fRequired.split(",");
var validRegExp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
var email = document.getElementById(fieldRequired).value;
if (email == "") {
alert("email cannot be empty");
return false;
}
else {
if (email.search(validRegExp) == -1) {
alert(" A valid E-mail is required");
return false;
}
else {
return true;
}
}
}
//This method is used to Generate Ids Dynamically
function getFieldRequired(tableID, hiddenFieldID, filedNamePrefix) {
try {
var returnValue = '';
var accRow = document.getElementById(hiddenFieldID).value;
if (accRow == null || accRow == '')
accRow = "'1'";
var arrayString;
arrayString = accRow.toString().split(",");
aFieldPrefix = filedNamePrefix.toString().split(",");
var I = parseInt(0);
var J = parseInt(0);
for (I = 0; I < arrayString.length; I++) {
for (J = 0; J < aFieldPrefix.length; J++) {
if (I == 0 && J == 0)
{
returnValue = aFieldPrefix[J] + arrayString[I].replace("'", "").replace("'", "");
}
else
{
returnValue = aFieldPrefix[J] + arrayString[I].replace("'", "").replace("'", "");
}
}
}
return returnValue;
}
catch (e) {
alert(e);
}
}
Use jquery for this, as it has cross browser support
$.each("#TableGridView tr td input",function(){
alert($(this).attr("id"));
});