I have a small question,
I am yet a beginner with Java Script and I don't have that much of knowledge with it. My question is:
I need to create a fake donation form. The form contains fields where the user can write his data like his phone number, donate amount etc... and when the user hit submit his donate amount and his name should be shown in a table, besides the last other 4 donations of the other people. I think that my code should look like that
<body>
<div id="container">
<form action="#" name="myForm" id="myForm">
<br>name: <input type="text" name="name" id="donatorName"></br>
<span id="Enter your name"></span>
<br>Donate amount: <input type="number" name="donateAmount" id="amount"></br>
<span id="Your total donate amount"></span>
<br/>
<button type="button" value="submit" onclick="return validation(); document.getElementById('container').style.display='none'">submit</button>
</form>
</div>
<div id="new_container">
<p id="displa_name"></p>
<p id="display_total_amount"></p>
<div id="Btn"></div>
</div>
<script type="text/javascript">
function validation(){
var donatorName = document.getElementById("donatorName").value;
var donateAmount = document.getElementById("amount").value;
// donatorName validation
if(donatorName == ""){
document.getElementById("donatorName").innerHTML = "Name cannot be empty";
document.getElementById("donatorName").style.color = "#ff0000";
return false;
}
// donateAmount validation
if(donateAmount == ""){
document.getElementById("amount").innerHTML = "Total amount cannot be empty";
document.getElementById("amount").style.color = "#ff0000";
return false;
}
if(donateAmount < 1){
document.getElementById("amount").innerHTML = "Donate amount should be greater than 0";
document.getElementById("amount").style.color = "#ff0000";
return false;
}
showDetails();
}
function showDetails(){
document.getElementById('container').style.display='none';
// name
const = document.getElementById("amount").value;
document.getElementById("display_name").innerHTML = `DonatorName: ${donatorName}`;
document.getElementById("display_total_amount").innerHTML = `TotalAmount: ${donateAmount}`;
</script>
</body>
I am not sure about my code, so please help me and explain to me how else I can do it. I want to keep it simple for now so please give me some advices :D
I recommend you use backend language for this, like PHP, but if javaScript is what you needed, here's a simple way for that.
You can store the data in an array, or cache them so that the data will not be lost even when tab is refreshed.
But let's use array for this example. You already have your form so let's skip it.
For the table in HTML:
<table>
<thead>
<th>Name</th>
<th>Amount</th>
</thead>
<tbody id="displayDonations">
<!-- Data will be displayed here thru javaScript -->
</tbody>
</table>
javaScript:
let donations = [];
function validation() { // This is called when you submit the form
// Put your validations here
// Example Validation: return false if not valid
if (!isValid()) return false;
// Remove first element of the array if length == 5
if (donations.length == 5) {
donations.shift();
}
// Push object into the donations array
donations.push(
{
"name" : document.getElementById("donatorName").value,
"amount" : document.getElementById("amount").value
}
);
showDetails();
}
function showDetails() {
let tableBody = "";
donations.forEach((element) =>{
// Construct what you want to display
tableBody += ""
+ "<tr>"
+ "<td>" + element.name + "</td>"
+ "<td>" + element.amount + "</td>"
+ "</tr>"
;
});
// Write the tableBody to the HTML
document.getElementById("displayDonations").innerHTML = tableBody;
}
Related
The onblur attribute is not working for form validation on an html page when I try to use a function in an external javascript file while the onclick attribute works. So, only the result function from the JS file is working. Please help me know why. Below is my html and js file.
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Maintenance request</title>
<script type="text/javascript" src="MaintainScript.js></script>
<link rel="stylesheet" type="text/css" href="maintainStyle.css">
</head>
<body>
<div id="banner"><h1 style="color:#FFFFFF;">Housing Maintenance Request</h1></div>
<form>
<table>
<tr>
<td>Name:</td><td><input type="text" id="name" onblur="name();"><span id="msg1"><span></td>
</tr>
<tr>
<td>Phone:</td><td><input onblur="phone();" type="text" id="phone" placeholder="xxx-xxx-xxxx"><span id="msg2"><span></td>
</tr>
<tr>
<td>Student ID:</td><td><input onblur="id();" type="number" id="Student ID"><span id="msg3"><span></td>
</tr>
<tr>
<td>Email:</td><td><input onblur="email();" type="text" id="Email" placeholder="email#mail.com"><span id="msg4"><span></td>
</tr>
<tr>
<td>Type of request:</td>
<td><select>
<option>A/C</option>
<option>Door Lock</option>
<option>Mirror</option>
<option>Shower</option>
<option>Light out</option>
<option>Room change</option>
<option>Pest issue</option>
<option>Mold</option>
</select></td>
</tr>
<tr>
<td>Room/Apt/Suite:</td><td><input onblur="room();" type="text" id="room"><span id="msg3"></span></td>
</tr>
</table>
<div class="comments"><center>Describe the problem</center><br><textarea cols=145 rows=7></textarea></div>
<div class="submit"><input type="button" onclick="result();" value="SUBMIT"></div>
<span id="end"></span>
</form>
</body>
And then the JS file:
function name(){
var response = document.getElementById("name").value;
if(response.length == 0){
document.getElementById("msg1").style.color = "Red";
document.getElementById("msg1").innerHTML = " You did not provide name";
}
else{
document.getElementById("msg1").style.color = "Green";
document.getElementById("msg1").innerHTML = "<strong> Valid</strong>";
}
}
function phone(){
var response = document.getElementById("phone").value;
var pattern = /^d{3}-d{3}-d{4}$/;
if(pattern.test(response)){
document.getElementById("msg2").style.color = "Red";
document.getElementById("msg2").innerHTML = " Provide number in xxx-xxx-xxxx format";
}
else{
document.getElementById("msg2").style.color = "Green";
document.getElementById("msg2").innerHTML = "<strong> Valid</strong>";
}
}
function id(){
var response = document.getElementById("id").value;
if(response.length == 0){
document.getElementById("msg3").style.color = "Red";
document.getElementById("msg3").innerHTML = " You did not provide a seven-digit id";
}
else{
document.getElementById("msg3").style.color = "Green";
document.getElementById("msg3").innerHTML = "<strong> Valid</strong>";
}
}
function email(){
var emailInput = document.getElementById("email").value;
var emailPattern = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
if (emailPattern.test(emailInput)){
document.getElementById("msg4").style.color = "Green";
document.getElementById("msg4").innerHTML = "<strong> Valid</strong>";
return (true);
}
else{
document.getElementById("msg4").style.color = "Red";
document.getElementById("msg4").innerHTML = " Invalid Email";
return (false);
}
}
function room(){
var response = document.getElementById("room").value;
var pattern = /^d{3}-s{1}$/;
if(patttern.test(response)){
document.getElementById("msg5").style.color = "Red";
document.getElementById("msg5").innerHTML = " You did not provide accurate room information";
return(true);
}
else{
document.getElementById("msg5").style.color = "Green";
document.getElementById("msg5").innerHTML = "<strong> Valid</strong>";
return(false);
}
}
function result(){
document.getElementById("end").innerHTML = "<center>Your request has been recorded. Please stay patient as the maintenance team prepares to work on it. Thanks.</center>";
}
There are several good reasons not to use onxyz-attribute-style event handlers. One of the many good reasons is that they run in an environment which is even more crowded with identifiers than the global environment — and that's saying something. The code is run as though it were in several with blocks including all of the properties of the element the onxyz-attribute appears on, its form, and the document (and then of course there are globals). The identifiers added to the scope by those (effective) with blocks have higher precedence than your global functions.
So for instance, in that environment, the name and id identifiers will resolve to the name and id properties of the element, not your global name and id functions. You can prove that to yourself here:
<script>
// (This is here rather than in the script pane
// because Stack Snippets correctly put the script
// *after* the HTML; want to match OP's question)
function name() {
}
function id() {
}
</script>
<div>Focus the field below, then unfocus it:</div>
<input type="text" id="foo" onblur="console.log('name = [' + name + '], id = [' + id + ']');">
Instead:
Put all your code in a scoping function so you're not creating a bunch of global functions.
Hook up your handlers using modern event handling, perhaps associating them by name or by data-* attribute.
Put your script at the end of the page so the elements are there when it runs (this is important for Step 2).
For instance, perhaps your phone field might look like this:
<input data-validate="phone" type="text" id="phone" placeholder="xxx-xxx-xxxx">
and your script might look like this:
(function() { // The beginning of the scoping function
var validators = {
phone: function phone() {
// ....
}
// ...and the others...
};
Array.prototype.forEach.call(document.querySelectorAll("input[data-validate]"), function(element) {
var vname = element.getAttribute("data-validate");
var validator = validators[vname];
if (validator) {
element.addEventListener("blur", validator, false);
} else if (typeof console !== "undefined" && console.error) {
console.error("Unknown data-validate value '" + vname + "'", element);
}
});
})(); // The end of the scoping function
(Using workarounds like this if you need to support old IE which doesn't have addEventListener.)
Example:
(function() { // The beginning of the scoping function
var validators = {
phone: function phone() {
console.log("Phone validation triggered");
}
// ...and the others...
};
Array.prototype.forEach.call(document.querySelectorAll("input[data-validate]"), function(element) {
var vname = element.getAttribute("data-validate");
var validator = validators[vname];
if (validator) {
element.addEventListener("blur", validator, false);
} else if (typeof console !== "undefined" && console.error) {
console.error("Unknown data-validate value '" + vname + "'", element);
}
});
})(); // The end of the scoping function
<div>Focus the field below, then unfocus it.</div>
<input data-validate="phone" type="text" id="phone" placeholder="xxx-xxx-xxxx">
Or, of course, use one of the many fine form validation libraries out there which have already been thoroughly designed and debugged.
i would like to know how i can make it so when people input something it goes in a bulleted list, in the middle of the screen. Like but in javascript?
I got my code from: How to display input back to the user on an HTML page?
<html><head></head><body>
<input id="title" type="text" maxlength="276" onkeyup="Allow()" >
<input type="submit" value="Save/Show" onclick="insert()" />
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var messageBox = document.getElementById("display");
function Allow(){
if (!user.title.value.match(/[a-zA-Z1-9]$/) && user.title.value !="") {
user.title.value="";
alert("Please Enter only alphabets");
}
}
function insert () {
titles.push(titleInput.value);
clearAndShow();
}
function clearAndShow () {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "To Do: " + titles.join(", ") + "<br/>";
}
</script>
</body>
</html>
jsbin example: https://jsbin.com/xahidolibu/edit?html,output
I've modified your code to:
create a list instead of comma deliminated string on clearAndShow()
added css to center align the list
jsbin: https://jsbin.com/lamebopidu/1/edit?html,css,output
I'm trying to get the text from a input textfield and place the value in a table row, but each time someone posts something the oldest post moves down 1 row, here's what I have but I'm very confused now
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--//
function thisPost(frm){
if (frm.postHere.value == "")
alert("Hey! You didn't enter anything!")
else
frm.postHere.value = ""
<table style="width:100%">
<tr>
<td>post + frm.postHere.value</th>
</tr>
</table>
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="thisPost">
<P>Post this: <INPUT TYPE="TEXT" NAME="postHere"><BR><BR>
<INPUT TYPE="Button" Value="Post" onClick="thisPost(this.form)">
</P>
</FORM>
</BODY>
</HTML>
Demo on Fiddle
HTML:
<label>Post this:</label>
<input type="text" name="postHere" />
<br />
<br />
<button>Post</button>
<table></table>
JavaScript:
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("postHere")[0];
var cnt = 0;
btn.onclick = function() {
if (!inpt.value) alert("Hey! You didn't enter anything!");
else alert("The field contains the text: " + inpt.value);
var tbl = document.getElementsByTagName("table")[0];
var row = tbl.insertRow(cnt++);
var cell = row.insertCell(0);
var txt = document.createTextNode(inpt.value);
cell.appendChild(txt);
};
There's a number of syntax errors in your code, so I'm not sure how you are able to run it in its current state. Also, your markup and approach is fairly dated. I would highly recommend investing time in a cross-browser DOM framework like jQuery and then an good front-end MVW and templating framework. That aside, I've re-worked your code into a more usable form. Hopefully this will get you going.
function thisPost(){
//Use getElementById to retrieve the DOM elements you're looking for
var txtPost = document.getElementById('txtPost');
var post = txtPost.value;
if (post == "") {
alert("Hey! You didn't enter anything!")
} else {
alert("The field contains the text: " + post);
//Get a reference to your table
var table = document.getElementById('posts');
//TODO: This is unsafe and subject to script injection.
//http://en.wikipedia.org/wiki/Code_injection#HTML_Script_Injection
table.innerHTML = '<tr><td>' + post + '</td></tr>' + table.innerHTML;
txtPost.value = "";
}
}
//from: http://stackoverflow.com/a/10150042/402706
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
//Don't bind events in your HTML markup, instead bind them in JavaScript.
addEvent(document.getElementById('btnPost'), 'click', thisPost);
table{
width:100%;
}
<form name="thisPost">
<p>
Post this: <input type="Text" name="postHere" id='txtPost'>
<br/><br/>
<input type="Button" value="Post" id='btnPost'/>
</p>
<table id='posts'>
</table>
</form>
I've ran into a pickle. I am writing a simple mortgage calculator that sends data to calc.php through ajax.
Using jquery, I am checking to make sure that the user enters the appropriate values in the requested fields; both purchase price and down payment should be numbers (working), down payment can't be greater than purchase price (working), when a term is selected, interest rate auto populates (working) and an error message appears if either term or interest rate aren't populated (working).
When user submits the form and any of the mandatory items are missing, error messages display advising... however, the form doesn't submit when errors are corrected by the user.
As you will soon see by looking at my not-too-sophisticated code, I am still learning Jquery and will appreciate any input you can give me.
Thanks in advance for the help.
HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="css/css.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"> </script>
<script type="text/javascript" src="js/js.js" charset="utf-8"></script>
</head>
<body>
<h1>Mortgage</h1>
<form action="calc.php" method="post" id="mortgage-form">
<p class="errorMessage" id="shouldBeNumber">*This value can only contain numbers</p>
<p id="pPrice"><span class="errorMessage" id="PPmustBeNumber">*</span>Purchase Price:
<input type="text" name="purchase-price" id="purchase-price" value="0"/>
<span class="errorMessage" id="purchasePriceError">Please enter a number value!</span>
</p>
<p id="dPayment"><span class="errorMessage" id="DPmustBeNumber">*</span>Down Payment:
<input type="text" name="down-payment" id="down-payment" value="0"/>
<span class="errorMessage" id="downPaymentError">Down payment value must be less than Purchase Price!</span>
</p>
<p id="term">
<select id="loan-term">
<option value="noValueSelected">-- Select a Term -- </option>
<option value="15yrs">15 Years</option>
<option value="20yrs">20 Years</option>
<option value="30yrs">30 Years</option>
</select><span class="errorMessage" id="termRequired"> * Term is required.</span>
</p>
<div id="interest-rate"></div>
<p><input type="submit" name="submit" id="submit" value="Calculate!" /></p>
</form>
<footer>
<p>
© Copyright by Ricardo
</p>
</footer>
</body>
</html>
Here's my JQUERY
$(function() {
//HIDE errors
$('.errorMessage').hide();
//Do something when loan-term changes
$('#loan-term').change(function(){
var loanTerm = $(this).val();
var interestOption = '';
//alert(loanTerm);
if (loanTerm == '15yrs') {
interestOption += "<option value='15yrFixed'>15 Year Fixed: 2.88% </option>";
} else if (loanTerm == '20yrs') {
interestOption += "<option value='20yrFixed'>20 Year Fixed: 3.52%</option>";
} else if (loanTerm == '30yrs') {
interestOption += "<option value='30yrFixed'>30 Year Fixed: 4.2%</option>";
}
if (loanTerm != "noValueSelected") {
var interestRate =
"<select id='interest-rate'><option value='selectInterestRate'>-- Select an Interest Rate -- </option>" + interestOption + "</select><span class='errorMessage' id='interestRequired'> * This field is required.</span>";
$('#interest-rate').html(interestRate).show();
} else if (loanTerm == "noValueSelected") {
$('#interest-rate').hide();
}
});//END loan-term check
$('#mortgage-form').submit(function() {
var purchasePrice = $('#purchase-price').val();
var downPayment = $('#down-payment').val();
var loanTerm = $('#loan-term').val();
var interestRate = $('#interest-rate').val();
function containsNumber(val) {
return /^(\d|,)+$/.test(val)
}
if (containsNumber(purchasePrice) == true && containsNumber(downPayment) == true ) {
$('#PPmustBeNumber').hide();
$('#DPmustBeNumber').hide();
$('#shouldBeNumber').hide();
//alert(purchasePrice + downPayment);
//CHECK IF DOWNPAYMENT IS LESS THAN PURCHASE PRICE.
if (downPayment < purchasePrice) {
$('#downPaymentError').hide();
} else {
$('#downPaymentError').show();
}
} else if (containsNumber(purchasePrice) == false){
$('#PPmustBeNumber').show();
$('#shouldBeNumber').show();
} else if (containsNumber(downPayment) == false) {
$('#DPmustBeNumber').show();
$('#shouldBeNumber').show();
}
if (loanTerm != "noValueSelected") {
$('#termRequired').hide();
$("#interest-rate").change(function() {
if (interestRate != "selectInterestRate"){
$('#interestRequired').hide();
} else if (interestRate == "selectInterestRate"){
$('#interestRequired').show();
}
})
} else if (loanTerm == "noValueSelected"){
$('#termRequired').show();
}
if ( purchasePrice && downPayment && loanTerm && interestRate) {
var data = new Object();
data.purchasePrice = purchasePrice;
data.downPayment = downPayment;
data.loanTerm = loanTerm;
data.interestRate = interestRate;
data.interestOption = interestOption;
//create an object of Ajax options:
var options = new Object();
//Establish each setting:
options.data = data;
options.dataType= 'text';
options.type = 'get';
options.url = 'calc.php';
//perform the request:
$.ajax(options);
}
return false;
}); //END SUBMIT FUNCTION
});
I would just let the form submit as normal without doing the ajax. The primary issue I see is that you don't have a way for the form to return true; which allows the form to actually submit. Try subbing out your submit function for this below and that should get the ball rolling for you.
$('#mortgage-form').submit(function () {
var purchasePrice = $('#purchase-price').val();
var downPayment = $('#down-payment').val();
var loanTerm = $('#loan-term').val();
var interestRate = $('#interest-rate').val();
function containsNumber(val) {
return /^(\d|,)+$/.test(val)
}
if (containsNumber(purchasePrice) == true && containsNumber(downPayment) == true) {
$('#PPmustBeNumber').hide();
$('#DPmustBeNumber').hide();
$('#shouldBeNumber').hide();
//alert(purchasePrice + downPayment);
//CHECK IF DOWNPAYMENT IS LESS THAN PURCHASE PRICE.
if (downPayment < purchasePrice) {
$('#downPaymentError').hide();
} else {
$('#downPaymentError').show();
}
} else if (containsNumber(purchasePrice) == false) {
$('#PPmustBeNumber').show();
$('#shouldBeNumber').show();
} else if (containsNumber(downPayment) == false) {
$('#DPmustBeNumber').show();
$('#shouldBeNumber').show();
}
if (loanTerm != "noValueSelected") {
$('#termRequired').hide();
$("#interest-rate").change(function () {
if (interestRate != "selectInterestRate") {
$('#interestRequired').hide();
} else if (interestRate == "selectInterestRate") {
$('#interestRequired').show();
}
})
} else if (loanTerm == "noValueSelected") {
$('#termRequired').show();
}
if (purchasePrice && downPayment && loanTerm && interestRate) {
var data = new Object();
data.purchasePrice = purchasePrice;
data.downPayment = downPayment;
data.loanTerm = loanTerm;
data.interestRate = interestRate;
data.interestOption = interestOption;
//create an object of Ajax options:
var options = new Object();
//Establish each setting:
options.data = data;
options.dataType = 'text';
options.type = 'get';
options.url = 'calc.php';
return true;
}
return false;
}); //END SUBMIT FUNCTION
if you are using jQuery's ajax functions, you don't need to submit the form. Also, if you want the form to submit, you need to put in an IF function to return true, or it won't submit. Your code simply returns false no matter what. You need to make it conditional, so if the errors are not displayed because the criteria is met by the user, THEN the form returns true and sends, yet you wouldn't need the ajax then, as I have mentioned.
Sample code to validate with jQuery and submit the form normally:
For this to work, I would change the submit button from type="submit" to type="button" which will prevent it from submitting automatically.
$('#submit').click(function(){
// put all your code to check inputs for errors here.
$('#mortgage-form').submit();
});
This way you can use javascript for the validation and then send the form to the calc.php page just how you need it to work.
Ok, So instead of using AJAX, I changed my code to simple JQUERY validation and then normal form submission (which is what I wanted). I changed the form from GET to POST. I am still using JQUERY to validate the form, and then just send the values once everything is OK.
PHP will then handle the equations.
Thank you to everyone's suggestion; you inspired me to solve my issue.
Cheers!
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>