How do I access elements across frames? - javascript

file1.html
<html>
<head>
<title>AIDS (Automated ID System)</title>
<HTA:APPLICATION
id="frames"
border="thin"
caption="yes"
icon="http://www.google.com/favicon.ico"
showintaskbar="yes"
singleinstance="yes"
sysmenu="yes"
navigable="yes"
contextmenu="no"
innerborder="no"
scroll="auto"
scrollflat="yes"
selection="yes"
windowstate="normal" />
<script language="javascript" type="text/javascript">
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
function getWindowsUserName()
{
var WinNetwork = new ActiveXObject("WScript.Network");
var urlToSite = createCustomURL(WinNetwork.UserName);
var frame = document.getElementById("psyncLink");
frame.onload = function() {
frame.onload = null;
if (requestingPassword()) {
//alert("password button screen");
passwordButtonScreen();
} else {
alert("direct password required");
}
}
frame.src = urlToSite;
}
function requestingPassword()
{
var btn = window.frames[1].document.getElementsByName("SUBMIT-password.pss");
if (btn.length == 0) {
return false;
} else {
return true;
}
}
function passwordButtonScreen()
{
var btn = window.frames[1].document.getElementsByName("SUBMIT-password.pss");
btn[0].click();
}
function createCustomURL(userName)
{
var customURL = "http://localhost/nph-psf.exe?HOSTID=AD&ALIAS=" + userName;
return customURL;
}
function Sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function whichScreen() {
var btn = window.frames[1].document.getElementsByName("SUBMIT-password.pss");
if (btn.length == 0) {
alert("no button!");
// User is at password screen
var textField = window.frames[1].document.getElementsByName("_MYPW");
textField[0].text = "";
return;
} else {
btn[0].click();
WaitSeconds(5);
var textField = window.frames[1].document.getElementsByName("_MYPW");
textField[0].value = "ios12sdk";
btn = window.frames[1].document.getElementsByName("SUBMIT-VERIFY");
btn[0].click();
}
}
var loadOtherFrame = function (text) {
getWindowsUserName();
alert(text);
};
</script>
</head>
<frameset cols="300px, *">
<frame src="leftframe.html" name="topo" id="topo" application="yes" />
<frame src="topo1.htm" name="psyncLink" id="psyncLink" application="yes" />
</frameset>
</html>
leftframe.html
<html>
<head>
<title>AIDS Assistant</title>
</head>
<script language="javascript">
function checkPassword() {
var validString = /^[a-z](?=[a-z]*[0-9])[a-z0-9]{0,6}[a-z]$/;
if (validString.test(document.getElementById("newPassword").value)) {
alert("The password is valid");
var validate = function () {
// validate textbox input ...
// call parent page function
parent.loadOtherFrame(document.getElementById("newPassword").value);
};
} else {
alert("The new password does NOT meet the requirements. Please try again.");
}
}
</script>
<body>
<table width="300px">
<tr>
<td>Type Your Old Password</td>
<td><input id="oldPassword" type="text" maxlength="8" /></td>
</tr>
<tr>
<td>Please type your new password</td>
<td><input id="newPassword" type="text" maxlength="8" min="8" /></td>
</tr>
<tr>
<td colspan="2"><input id="checkOldPassword" type="button" title="Check New Password" value="Check New Password" onclick="checkPassword()" /></td>
</tr>
</table>
</body>
</html>
Let me clarify what I am doing
leftframe.html needs to validate a textbox
Once the left frame has been processed. It needs to notify the parent window, file1.html, so it can load the second frame (topo1.htm)
topo.htm doesn't exist so the HTA app loads Page could not be found for that specific frame but it should change when we call function getWindowsUserName() from loadOtherFrame. The loadOtherFrame is called from the leftframe.html file as tjscience indicated.
When I run the HTA, the loadOtherFrame is being called (before the button click on leftframe.html)

I assume your framesetis not in the frame already. You can access all frames via top.window.frame_name from any frame or top.window itself.
form_in_psyncLink=top.window.psyncLink.document.getElementById('form_id');
EDIT
If this external page is not in the same domain, you can't acces it's content by regular means. Read more about Same origin policy for JavaScript. (AFAIK HTA doesn't change this behavior.)
My example above gives you a reference to the psyncLink, naturally you'll use it in your validating script to access elements in psyncLink to "paste" data. (which in this case maybe impossible due to the cross-domained pages)

Edit to include passing text input along to parent page
You can call a function in the parent page from the frame when the textbox is validated:
JS IN Leftframe.html
<script type="text/javascript">
var validate = function () {
// validate textbox input ...
// call parent page function, passing the text from the input
parent.loadOtherFrame(text);
};
</script>
JS in file1.html
<script type="text/javascript">
var loadOtherFrame = function (text) {
// load other frame here ...
};
</script>

Related

Omitting the fields with no value

I need to publish exam result from a Google sheet. The search button shows the marks obtained perfectly if roll no is provided at the box but I need to omit the fields with no value like Subject 3, 5 etc. with their textbox from the html page
Here is the sheet I'm using and the code I'm using ...
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/16IH3yKJjLwM9XA0c4_BN5MVQSKh8hV7gR6_kLLfe8to/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
});
return values[0];
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
.hidden {
display:none;
}
</style>
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
Name <input type="text" id="name"/><br>
Roll <input type="text" id="roll"/><br>
Subject 1 <input type="text" id="sub1"/><br>
Subject 2 <input type="text" id="sub2"/><br>
Subject 3 <input type="text" id="sub3"/><br>
Subject 4 <input type="text" id="sub4"/><br>
Subject 5 <input type="text" id="sub5"/><br>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
document.getElementById('sub1').value = values[2];
document.getElementById('sub2').value = values[3];
document.getElementById('sub3').value = values[4];
document.getElementById('sub4').value = values[5];
document.getElementById('sub5').value = values[6];
}
</script>
</html>
I need to omit the Subject name and the text box with no value from the HTML page. And "Nothing Found" should be shown if a roll searched which is not in the table. It's not required but will be good if the Subject names come from sheet's row 1.
What should I do?
There are two ways to go about this:
Create your HTML on the server side (as #Cooper said)
Manipulate your HTML with JavaScript
To create your HTML on the server side you can use string and "write" the html automatically.
Then your functions will be something like this:
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(response) {
document.getElementById("divid").innerHTML=html
});
If you absolutely want to manipulate the HTML on the client-side, you will use something like this:
function toggleElement(id) {
var td = document.getElementById(id).parentElement;
var tr = td.parentElement;
tr.classList.toggle("hidden");
}
the usage is like so:
function fillInfo(values) {
document.getElementById('name').value = values[1];
document.getElementById('roll').value = values[0];
for (var i=0;i<values.length-2;i++) {
if (values[i+2]==null) {
toggleElement("sub"+i);
} else {
document.getElementById("sub"+i).value = values[i+2];
}
}
//rest of the code here
}
and then you will have some css that does this:
.hidden {
display:none;
}
Edit:
This is how you implement the first solution:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txtName"/>
<button id="show">SHOW</button>
<h1>FMATS</h1>
<div id="dataDiv"></div>
</body>
<script>
//When click on show button it will run search function
window.onload = function(e){
document.getElementById('show')
.addEventListener('click', search);
}
//Get the value for txtName input and run search function in code.gs
function search() {
var txtName = document.getElementById('txtName').value;
google.script.run.withSuccessHandler(fillInfo).withFailureHandler(function (e) { console.log(e) }).search(txtName);
}
//It will run when a success response comes from search function in code.gs and updates the input with the sheet info
function fillInfo(values) {
console.log(values);
document.getElementById("dataDiv").innerHTML=values
}
</script>
</html>
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
//Search for the id and return the array for that row
function search(id) {
var ss = SpreadsheetApp.openByUrl("SHEETS URL");
var sheet = ss.getSheetByName("Sheet1");
var values = sheet
.getDataRange()
.getValues()
.filter(function(row) {
return row[0] == id;
})[0];
var legends = sheet.getRange(1,1,1,sheet.getMaxColumns()).getValues()[0];
return createHTML(legends, values);
}
function createHTML(legends, values) {
Logger.log(legends);
var htmlResult = "";
for (var i=0; i<values.length; i++) {
if (values[i]!=null && values[i]!=="") {
htmlResult += '<div class="field">' + (legends[i]+"").replace("Sub", "Subject ") + '<input type="text" id="sub1" value="'+values[i]+'"></div>';
}
}
return htmlResult;
}
Hope this helps!
Here's a simple example of a complete solution of your problem done mostly server side.
I like do it this way because I like to be able to use Utilities.formatString().
Server Functions:
File: aq3.gs:
function search(sObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getDataRange();
var vA=rg.getValues();
var hA=vA[0];
var dObj={dA:[]};
for(var i=1;i<vA.length;i++) {
if(vA[i][0]==sObj.roll) {
var row=vA[i];
for(var j=0;j<hA.length;j++) {
dObj[hA[j]]=row[j];
}
break;
}
}
var html="<style>input{margin:2px 5px 0 2px}</style>";
for(var i=0;i<row.length;i++) {
if(dObj[hA[i]]) {
html+=Utilities.formatString('<br /><input id="txt-%s" type="text" value="%s" /><label for="txt-%s">%s</label>',i,dObj[hA[i]],i,hA[i]);
}
}
sObj['results']=html;
return sObj;
}
Run the below function to get the dialog running. The enter the roll you wish to see in the search box and click the search button. You will get only the boxes that have data.
function launchExamResultsSearchDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq5');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Exam Results");
}
The html:
File: aq5.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function search() {
var text=$('#srchtext').val();
google.script.run
.withSuccessHandler(function(sObj) {
document.getElementById("results").innerHTML=sObj.results;
})
.search({roll:text});
}
console.log("My Code");
</script>
</head>
<body>
<input type="text" id="srchtext" /><input type="button" value="Search" onClick="search();" />
<div id="results"></div>
</body>
</html>
This is what the dialog looks like:
You can just keep changing the search roll number and the dialog will replace the data with the new data. You can control the subjects by changing the headers.
Client To Server Communication
Utilities.formatString()

If condition not working in form validation

This is a question from my elder brother's question paper which I'm trying to solve but I am not able to do so .
Create a form containing a two Text fields and radio button and submit button. Name the
text fields account number and amount and radio button as transaction (deposit ,withdraw
and enquiry).Write a JavaScript the validates the text field to have only numbers, the first
text field should be of size 10 and second text field should have values between 500 to
20,000. Using onclick event a jQuery is called that performs necessary transactions and
display the updated value.
.............................................................................
So I have written the following code:
form1.html
<!DOCTYPE html>
<html>
<head>
<title>Web Tech DA 1</title>
<script type="text/javascript" src="script1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function() {
var acc=document.getElementById("acc").value;
var amt=document.getElementById("amt").value;
var bal=acc%100;//balance , I am using this to dynamically generate a new balance each time a new account number is entered
$("#t1").click(function(){
bal=acc+amt;
alert(bal);
});
$("#t2").click(function(){
if(acc>amt){
bal=acc-amt;
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
$("#t3").click(function(){
alert(bal);
});
});
});
</script>
</head>
<body>
<form name="myform" onsubmit="if(validateform()) {window.alert('succefully submitted')} else {return false;}" >
<p>Account Number : <input type="text" maxlength="10" name="acc" id="acc" height="20px" width="100px" required="required" onblur="validacc(this.value)"></p>
<p>Amount : <input type="text" name="amt" id="amt" height="20px" width="100px" required="required" onblur="validamt(this.value)"></p>
<p>Transaction : <input type="radio" name="trans" id="t1" value="deposit" />Deposit
<input type="radio" name="trans" id="t2" value="withdraw" />Withdraw
<input type="radio" name="trans" id="t3" value="enquiry" />Enquiry </p>
<input type="submit" name="sub" id="sub" value="Submit">
</form>
</body>
main1.css
*{
margin:0;
padding: 0;
}
body{
margin: 25px;
}
form p {
margin: 10px;
}
form input {
margin: 10px;
}
script1.js
function validateform() {
var acc = document.getElementById("acc").value.trim();
var amt = document.getElementById("amt").value.trim();
if(validregno(acc)&&validname(amt))
{window.alert("No errors found");return true;}
else
{window.alert("invalid entries found");return false;}
}
// Overall Go
function validacc(r)
{
var p = new RegExp(/^[0-9]{10}$/i);
if(!p.test(r))
{
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt)
{
var p = new RegExp( /^[0-9]{1,}$/);
if(amt>=500 && amt<=20000){
if(p.test(n))
{
chngborderr("amt");
return false;
}
else
{
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i)
{
document.getElementById(i).style.borderColor="red";
}//red color means wrong format
function chngborderr(i)
{
document.getElementById(i).style.borderColor="green";
}//green color means correct format
For some reason I'm not able to enter a number in the "Amount" text field and none of the radio buttons are working .
Please point out any mistakes that I have done here .
P.S. I'm new to jQuery and form validation
UPDATE
I made the changes pointed out and even then for some reason the "Amount" text field doesn't get validated and the "submit" button resets the form .
I am analysing your code. if this is exactly what you have, I can notice that
1 - You did not include jQuery library in the of you.
you can do it by adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> or <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> inside the <head> element
2 - I think it is better to add and Else in onsubmit event of #myForm
if(validateform()) window.alert('succefully submitted'); else return false.
3 - I have never seen a javascript (.js files) variable declaration starting by int: they start with var keyword regardless the type of the variable
Here is a working code.
script1.js
function validateform() {
var accValue = document.getElementById("acc").value.trim();
var amtValue = document.getElementById("amt").value.trim();
if (validacc(accValue) && validamt(amtValue))
{ window.alert("No errors found"); return true; }
else
{ window.alert("invalid entries found"); return false; }
}
// Overall Go
function validacc(r) {
var p = new RegExp(/^[0-9]{10}$/i);
if (!p.test(r)) {
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt) {
var p = new RegExp(/^[0-9]{1,}$/);
var amtValue = document.getElementById("amt").value;
if (amtValue >= 500 && amtValue <= 20000) {
if (p.test(n)) {
chngborderr("amt");
return false;
}
else {
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i) {
document.getElementById(i).style.borderColor = "red";
}//red color means wrong format
function chngborderr(i) {
document.getElementById(i).style.borderColor = "green";
}
//Script inside your html file
$(document).ready(function () {
$('#sub').click(function() {
var accValue = document.getElementById("acc").value;
var amtValue = document.getElementById("amt").value;
var bal = accd % 100;})
$("#t1").click(function(){
bal = Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
});
$("#t2").click(function(){
if(acc > amt){
Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
});

Inline form Validation

I'm trying to get my form to validate inline but can't seem to get the right syntax, at the moment I have this, which does nothing yet. The first function, formhandler is meant to change the span elements text if the element gets blured and take away the error text once the field is focused at the moment it does neither of these.
<html>
<script type = "text/javascript">
document.getElementById("form").onfocus = function formHandler() {
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].focus()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = true;
}
else if(document.getElementById("form").elements[i].blur()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
}
function validate() {
var valid = false;
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].value == "") {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = true;
}
else{
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = false;
}
}
}
}
document.getElementById("form").onsubmit = validate;
</script>
<head>
<title>Question 1 / Vraag 1 - Basic JavaScript Validaton / Basiese JavaScript validasie
</title>
<link rel="Stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="get" action="" id = "form">
<table>
<tr>
<td> Firstname:</td>
<td> <input type="text" name="firstname" id="firstname" /><span id="fnError">
</span></td>
</tr>
<tr>
<td> Surname:</td>
<td> <input type="text" name="surname" id="surname" /><span id="snError">
</span></td>
</tr>
<tr>
<td> Age:</td>
<td> <input type="text" name="age" id="age" /><span id="aError">
</span></td>
</tr>
<tr>
<td> Email:</td>
<td><input type="text" name="email" id="email" /><span id="eError">
</span></td>
</tr>
<tr><td colspan="2"><input type="button" value="Validate" onclick = "validate()"/></td></tr>
</table>
</form>
</body>
</html>
I'm trying to achieve this without the use of jquery, so please don't suggest it, thanks in advance.
These are problems I found in your code:
Line 1: Forms don't have a .focus method. What did you mean for that to do?
Line 2: Change .length to .elements:
for (var i = 0; i < document.getElementById("form").elements.length; i++ ) {
var node = document.getElementById("form").elements[i];
...
The elements in the form are now aliased as node.
Lines 4: The .focus/.blur method doesn't return true if the element is out of focus. We're going to have to do it ourselves:
node.onfocus = function() { this.isInFocus = true; };
node.onblur = function() { this.isBlurred = !this.isInFocus; };
The resulting code is as follows:
if ( node.isInfocus ) { ... }
else if ( node.isBlurred ) { ... }
Line 9: Refer to above.
Wrap the code in a window.onload to be able to use the DOM elements when the DOM has loaded.
This is your revised code; let me know if it works for you:
var nodes = document.getElementById('form').elements, node;
for ( var i = 0; i < nodes.length; i++ ) (function(i) {
nodes[i].onfocus = function() { this.isInFocus = true; };
nodes[i].onblur = function() { this.isBlurred = !this.isInFocus; };
})(i);
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.type == 'text') {
if (node.isInFocus) {
var onode = node.nextSibling;
onode.innerHTML = "";
valid = true;
} else if (node.isBlurred) {
var onode = node.nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
First major problem: you are trying to do all of this in the initial script load. The main DOM is not yet loaded at that time so document.getElementById("form") won't find anything. Do the function definitions in an onload handler.
Also, not sure what you are expecting "valid" to bind to in the first function. Finally, once you have determined validity or not, you need to do something with the result.
You are referencing dom elements which don't exist yet. One solution would be to move all your <script> tag before </body>, so elements exist when the script is executed.
Another way, with pure javascript would be to do this:
<script>
window.onload = function(){
//All your code here
}
</script>
(The validate function could be outside if you want)
Cheers

I Want Pop Up Window To Appear If No Validation Errors

I have a button known as "Prepare Questions". Now when I click on this button, this button does two things, using the validaton() function it validates the form so that if there is an error in the form (empty textbox and radio button not selected) then it displays the suitable error messages on the page. But also the button uses the "openSessionPopup" function so that it opens up a pop up window which states the word "Session".
The problem is that when I click on the button it does both functions, so it displays validation errors if there is some and also opens up the pop up window.
What I want to do is that the pop up window should only be displayed after there are no validation errors. But I can't seem to get this to work, does anyone else know how to do this.
Below is my code:
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
function validation() {
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
}else{
errTimeMsgO.innerHTML = "";
}
}
function openSessionPopup (session) {
window.open(session,
'window',
'width=500,height=500,scrollbars=yes,status=no');
}
</script>
</head>
<body>
<form action="create_session.php" method="post">
<table>
<tr>
<th>Number of Sessions :</th>
<td class="sessionNo"><input type="radio" name="sessionNo" value="1" />1</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="2" />2</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="3" />3</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="4" />4</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="5" />5</td>
</tr>
</table>
<div id="radioAlert"></div>
<p><input type="text" id="datepicker" >
<br/><span id="dateAlert"></span></p>
<p><input type="text" id="timepicker" >
<br/><span id="dateTimeAlert"></span><span id="timeAlert"></span></p>
<p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="validation();openSessionPopup(this.href); return false" /></p>
</form>
</body>
First you should move your event handlers out of your html markup.
Next you should bind an event handler to that click event.
After that you should modify your validation method to return true or false to denote if it passed validation or not.
Last you should use that validation result in a conditional wrapping your showpopup method invocation.
Something like
function myClickHandler(){
if(validation()){
showSessionPopup();
}
}
for your handler and this how how you would bind it
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
Finally you would modify your validation method like so
function validation() {
var result = true;
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
result = false;
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
result = false;
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
result = false;
}else{
errTimeMsgO.innerHTML = "";
}
return result;
}
This will make your validation() method return false if you have errors.

How to write data from Form in HTML to XML with Javascript

This is an assignment from my class. What I need to do is create a registration page. When the user presses the submit button, I have take all the information on the form and write it to an existing XML file using Javascript. This is done on the client side, only through HTML, Javascript, and XML. By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves. Also, I'm not too familiar with Javascript, especially with the built in functions, if possible please explain what each line or method of code is doing.
Let me begin, here's how my existing XML looks like:
<?xml version ="1.0" encoding="utf-8" ?>
<!--GGFGFGFVBFVVVHVBV-->
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" personid="111" FirstName="Bob" LastName="Smith" DOB="01/01/1960" Gender="M" Title="Hello1">
</Person>
<!-- several more lines of <person> here -->
</PersonInfo>
When saving the form data, it has to follow all the layout within , basically I would need Usrname, Pswd, personid, and so on.
Basically, from what I understand, I have to create the XML line "Person" from my registration page once I press submit. Then push it to the array that already have my XML information, then write over my XML document with the information on the array. My problem is, I have exactly no idea how to do that.
For those who wants to know how my registration page looks like, here it is:
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<div class="form">
<form id="Registration" action="" method="get">
Username:<input type="text" name="usrname" maxlength="10"/> <br/>
Password:<input type="password" name="pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PID" /> <br>
<hr>
First Name:<input type="text" name="fname"/> <br>
Last Name:<input type="text" name="lname"/>
<hr>
DOB:<input type="text" name="dob" /> <br>
<hr>
Gender:<input type="text" name="sex" /> <br>
<hr>
Title:<input type="text" name="title" /> <br>
<hr>
Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
By the way, I know certain information on my HTML document may not be worded properly, so do hope you guys don't mind. Also, I would also have to fix up my XML later by putting the answer to the secret question within later.
Alright, thanks a lot in advance guys.
UPDATE!!!
Here we go, I finally figured out how to create an XML document with Javascript, here's the code:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
What this code here is doing is that, it takes my original XML file and loads it up into an array so it can create a new XML file. Basically I got the creating the XML file part down, but still need help with the rest of my stuff.
My goal is trying to take my form data and push it into my existing array, not overwrite it, add to it, so I can update my existing XML file with the new registration information. This is where I have absolutely no idea how to do. Some pointers would be nice.
By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves.
Which should give you a hint about searching a bit more deeply. Anyhow, I'm not going to comment on every line, but I will offer some hints.
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
That is a Microsoft proprietary way of creating an XML document and it is normally wrapped in try..catch as different ActiveXObjects are provided in different versions of IE. You also need to look for document.implementation.createDocument.
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
You might want to check out the async parameter.
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
It is considered better practice to use an array literal: ... = [];
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
Getting the length of xmlObj.childNodes on every loop is inefficient, consider storing the length and comparing with that value.
{
var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"),
xmlObj.childNodes(x).getAttribute("Pswd"),
xmlObj.childNodes(x).getAttribute("FirstName"),
xmlObj.childNodes(x).getAttribute("LastName"),
xmlObj.childNodes(x).getAttribute("DOB"),
xmlObj.childNodes(x).getAttribute("Gender"),
xmlObj.childNodes(x).getAttribute("Title"));
It is very inefficient to access xmlObj.childNodes(x) repeatedly. Store a reference and reuse it.
arrPerson.push(tmpArr);
You could assign the values directly to arrPerson and get rid of tmpArr.
x++;
Using a plain for loop will increment x for you.
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
Not all browsers will let you style the background color of input elements.
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
You might want a better way of naming the error messages and relating them to other information for that message. An object might do the job.
var msg = "You have logged in successfully";
var errCount = 0;
var usrn = document.getElementById("usrname1").value;
var pswd = document.getElementById("pswd1").value;
errCount += LogInVal(objForm.usrname);
errCount/*1*/ += LogInVal(objForm.pswd);
initialize_array();
if (errCount != 0)
{
alert(errmsg);
return false;
}
else if(authentication(usrn, pswd) == true)
The function authentication() returns true or false, so you don't need to compare it to anything, you can just test the returned value (i.e. there is no need for == true above).
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
Instead of showing alert messages one at a time in an alert, consider putting them in the document adjacent to the elements they relate to. That way the user can see the messaeg while fixing the error.
Isn't it cheating to ask us? Your implementation will probably only work in IE, I'd recommend using jQuery as it is impressively powerful at parsing XML.
I'm not sure why he wants you to write out XML as it's not very intuitive coming from JavaScript. You can do something like this via jQuery
//I capture form submitevent
$('form').submit(function( ev ){
ev.preventDefault(); //I keep form from submitting
$( xmlDocument ).find('Person').attr({
username: $("input[name=usrname]),
password: $("input[name=pswd]),
//and so on
});
});
It's up to you on how you 'report' this xml file
Here i am sharing my experience in writing html form data to xml.
Create one html file in one location (D:\\HtmlToXml.html).
And open it with Internet Explorer.
Then after provide information and click on submit button, then one file is created in the same directory with name example.xml.
If once an xml is created, then next time onwards on submit button click data will append to same xml file.
<!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>

Categories