trouble with delete user input - javascript

I'm trying to make an array that saves to local storage and the user can sort the items, add an item, delete an item, and clear the local storage. I'm having a lot of trouble getting the delete or splice user input to work can someone please provide me with some advice.
This is the code I have so far please forgive me if it's bad, definitely keen to know how it can be made better.
...
<script>
//lets my program know the books1 variable is an array
var books1 = []
//lets my program know the result variable is a string
var result = ""
//checks to see if the localstorage key booksArray exists, if it doesn't books1 has 3 books added ans is stored locally with a key of booksArray
if (localStorage.getItem("booksArray") == null) {
books1 = ["book1", "book2", "book3", "m", "p"]
localStorage.setItem("booksArray", JSON.stringify(books1))
// var theArray = JSON.parse("booksArray")
}
else {
loadBooks(); //loads the books to an array with variable name listBooks
}
function loadBooks() {
var result = localStorage.getItem("booksArray")
var listBooks = JSON.parse(result)
}
function sortBooks() {
var sortedBooks1 = localStorage.getItem("booksArray")
var sortedBooks2 = JSON.parse(sortedBooks1)
// loadBooks may work but haven't got it to yet. try redoing the project on books Array 2.2
sortedBooks2.sort()
document.getElementById("display1").innerHTML = sortedBooks2
localStorage.setItem("booksArray",JSON.stringify(sortedBooks2))
}
function addBook() {
var test1 = localStorage.getItem("booksArray")
var addedBook = document.getElementById("inputData").value
var addedBook2 = JSON.parse(test1)
addedBook2.push(addedBook)
document.getElementById("display1").innerHTML = addedBook2
localStorage.setItem("booksArray", JSON.stringify(addedBook2))
}
function delBook() {
//if (document.getElementById("inputData").value.length > 0) {
var local = localStorage.getItem("booksArray")
var delItem = document.getElementById("inputData").value
var array = JSON.parse(local)
var x = array.indexof(delItem);
//test2.splice(delItem,1)
if (delItem != -1) {
delete booksArray[delItem]
}
document.getElementById("display1").innerHTML = test2
}
// my test function
/* function displaybooks() {
var test1 = localStorage.getItem("booksArray")
var test2 = JSON.parse(test1)
document.getElementById("display1").innerHTML = test2[2]
}
*/
function clearLocal() {
localStorage.clear()
}
</script>
...
<body>
<!--i need to make the page so onload it displays the books--->
<form>
<input type="text" id="inputData" />
</form>
<input type="button" onclick="delBook()" value="delete your books" />
<input type="button" onclick="sortBooks()" value="test me" />
<input type="button" onclick="addBook()" value="add your book" />
<input type="button" onclick="clearLocal()" value="clear local storage" />
<p id="display1"></p>
</body>
</html>

You Can Try This Code For CRUD Operation For JSON data
$(function(){
var operation = "A"; //"A"=Adding; "E"=Editing
var selected_index = -1; //Index of the selected list item
var tbClients = localStorage.getItem("tbClients");//Retrieve the stored data
tbClients = JSON.parse(tbClients); //Converts string to object
if(tbClients == null) //If there is no data, initialize an empty array
tbClients = [];
function Add(){
var client = JSON.stringify({
ID : $("#txtID").val(),
Name : $("#txtName").val(),
Phone : $("#txtPhone").val(),
Email : $("#txtEmail").val()
});
tbClients.push(client);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was saved.");
return true;
}
function Edit(){
tbClients[selected_index] = JSON.stringify({
ID : $("#txtID").val(),
Name : $("#txtName").val(),
Phone : $("#txtPhone").val(),
Email : $("#txtEmail").val()
});//Alter the selected item on the table
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("The data was edited.")
operation = "A"; //Return to default value
return true;
}
function Delete(){
tbClients.splice(selected_index, 1);
localStorage.setItem("tbClients", JSON.stringify(tbClients));
alert("Client deleted.");
}
function List(){
$("#tblList").html("");
$("#tblList").html(
"<thead>"+
" <tr>"+
" <th></th>"+
" <th>ID</th>"+
" <th>Name</th>"+
" <th>Phone</th>"+
" <th>Email</th>"+
" </tr>"+
"</thead>"+
"<tbody>"+
"</tbody>"
);
for(var i in tbClients){
var cli = JSON.parse(tbClients[i]);
$("#tblList tbody").append("<tr>"+
" <td><img src='edit.png' alt='Edit"+i+"' class='btnEdit'/><img src='delete.png' alt='Delete"+i+"' class='btnDelete'/></td>" +
" <td>"+cli.ID+"</td>" +
" <td>"+cli.Name+"</td>" +
" <td>"+cli.Phone+"</td>" +
" <td>"+cli.Email+"</td>" +
"</tr>");
}
}
$("#frmCadastre").bind("submit",function(){
if(operation == "A")
return Add();
else
return Edit();
});
List();
$(".btnEdit").bind("click", function(){
operation = "E";
selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
var cli = JSON.parse(tbClients[selected_index]);
$("#txtID").val(cli.ID);
$("#txtName").val(cli.Name);
$("#txtPhone").val(cli.Phone);
$("#txtEmail").val(cli.Email);
$("#txtID").attr("readonly","readonly");
$("#txtName").focus();
});
$(".btnDelete").bind("click", function(){
selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
Delete();
List();
});
});
body{
font-family:Tahoma;
}
ul{
list-style:none;
}
ul label{
width:100px;
float:left;
}
#frmCadastre{
border:solid 1px;
}
#tblList{
width:100%;
border:solid 1px;
text-align:left;
border-collapse:collapse;
}
#tblList tbody tr{
border:solid 1px;
height:30px;
}
#tblList thead{
background:beige;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
<form id="frmCadastre">
<ul>
<li>
<label for="txtID">ID:</label>
<input type="text" id="txtID"/>
</li>
<li>
<label for="txtName">Name:</label>
<input type="text" id="txtName"/>
</li>
<li>
<label for="txtPhone">Phone:</label>
<input type="text" id="txtPhone"/>
</li>
<li>
<label for="txtEmail">Email:</label>
<input type="text" id="txtEmail"/>
</li>
<li>
<input type="submit" value="Save" id="btnSave"/>
</li>
</ul>
</form>
<table id="tblList">
</table>
</body>
</html>

try this clearLocal method and change(correct) in indexOf
function delBook() {
var x = array.**indexOf**(delItem);
}
function clearLocal() {
localStorage.clear()
document.getElementById("display1").innerHTML = "";
}

The local storage API contains a method for removing a single item: removeItem( key). So to delete your delItem you want to do:
localStorage.removeItem(delItem);

Related

Checkboxes and localStorage

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!
New to all this so be gentle please.
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
function save() {
//enter iteration sequence
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>
To retrieve all elements you can use document.querySelectorAll and pass as argument the filter that will do the job. In this case you want to retrieve all htlm elements that have the type attribute value equals to checkbox. After the retrieval of all elements that have type="checkbox", you should traverse all elements of list. And for each element you should store the id of checkbox as key and the checked of the checkbox asvalue in localstorage.
Below is the code:
<script>
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
And below is the code for updating the checkboxes with value we stored in localstorage.
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99.com/cookies-in-javascript-ultimate-guide.html.
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
VERSION WITH LOCAL STORAGE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
</body>
</html>
VERSION WITH COOKIE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(accessCookie(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
createCookie(el.id, el.checked,1);//1 is the day to expire
console.log(el.id,el.checked);
})
}
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
</script>
</body>
</html>
Just pass a different id in to document.getElementById.
Make sure to use a different key for localStorage.setItem so you don't overwrite a different value.
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.
Alternatively you could use a for loop and loop for as many items as you wish to save
On every save you can create an object with checkbox identification and values, save t in localStorage, on reloading, get the the whole object by a single key, parse it, loop through and set values
function save() {
//enter iteration sequence
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var obj = {};
for (i = 0; i < checkboxes.length; i++) {
obj[checkboxes[i].id] = checkboxes[i].checked
}
localStorage.setItem("box", JSON.stringify(obj));
}
//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);
Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.
Your code with fixing script
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />
<script>
function save() {
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checkbox2 = document.getElementById("whatever-2");
localStorage.setItem("whatever-2", checkbox2.checked);
}
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked;
</script>

how to keep code running after last function executed, im a newbie to this sorry if doesnt make sense

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Assignment 3 </title>
<script src="../JAVASCRIPT/question2.js" defer></script>
</head>
<body>
<h1>Shopping List</h1>
<input type="text" id="firstname" >
<input type='submit' onclick='changeText2()' value='Add Item' />
<input type="text" id="delitem" >
<input type='button' onclick='getNames()' value='Delete Item' />
<br><ol id="demo"></ol>
<input type='button' onclick='delevrytin()' id="evetang" value='Delete all' />
</body>
</html>
var list = document.getElementById('demo'); //demo is the organised list
//this function is for the add button
function changeText2() {
var firstname = document.getElementById("firstname").value
// the if satatement alerts if input is blank
if ((firstname == "") || (firstname == null)) {
alert("can't be blank");
return; //alerts if noting is inputed and add is clicked
}
//creates a list item
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
document.getElementById('firstname').value = ''; //clears textbox
}
// this function clears specific item starting from 0
var list = document.getElementById('demo');
function getNames()
{
var remov = document.getElementById('delitem').value;
list.removeChild(list.childNodes[remov]);
}
//delete all button
function delevrytin()
{
document.getElementById('demo').remove;
}
my problem is the delevrytin function when clicked
it works but stops the other functions from working.
Can anyone solve my problem emphasized text would be greatly appreciated
all good its running for me now
few variables and id's changed
var list = document.getElementById('org'); // var for the organized list gets it by id
//this function is for the add button
function changeText2() {
var firstitem = document.getElementById("firstitem").value
// the if statement alerts if input is blank
if ((firstitem == "") || (firstitem == null)) {
alert("can't be blank");
return; //alerts if noting is inputed and add is clicked
}
//creates a list item
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstitem));
list.appendChild(entry);
document.getElementById('firstitem').value = ''; //clears textbox
}
// this function clears specific item starting from 0
function getNames()
{ // creates a variable and assigns it to the delitem input
var remov = document.getElementById('delitem').value;
//remove - 1 lets you delete the list item but the number beside it
list.removeChild(list.childNodes[remov = remov - 1]);
}
//delete all button
function delevrytin()
{ //if there is a child node remove it
while (list.firstChild) {
list.removeChild(list.firstChild);
}
}

jQuery: Append string values from forms

Bonjour, I am working on a jQuery project with the following scenario:
1/ There are 3 forms on the landing page for user to enter 3 different names.
2/ When user enter a name (#term1/term2/term3) in any of the #form, an image associated will appear.
The order of entering the names should not be restricted.
Eg. If user enters "Karen" in one of the forms, the name "Karen" will be printed and an associated image will be printed. If user enter "Baby Kevin", the name "Baby Kevin" will be printed next to "Karen" (ideally with a comma separating the names) and an associated image will be added next to the previous image.
I have encountered a problem where:
When a name is being entered, it would print the whole string of all the formsrather than appending it.
Eg. If I have entered "Wallace" previously, and when I enter "Karen" in another #form after, it would print "WallaceWallaceKaren".
If I submit the #form with the #button, the associated image would not show.
$(document).ready(function () {
$("#info").hide();
var displayContent = function () {
$("#info").show();
var content1 = $('#term1').val();
content1 = content1.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content2 = $('#term2').val();
content2 = content2.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content3 = $('#term3').val();
content3 = content3.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var name1 = content1;
var $nameText1 = $("#name"),
str = name1;
html = $.parseHTML(str),
nodeNames = [];
$nameText1.append(html);
var name2 = content2;
var $nameText2 = $("#name"),
str = name2;
html = $.parseHTML(str),
nodeNames = [];
$nameText2.append(html);
var name3 = content3;
var $nameText3 = $("#name"),
str = name3;
html = $.parseHTML(str),
nodeNames = [];
$nameText3.append(html);
}
$('#search').click(displayContent);
$('#term1').keypress(function (event) {
if (event.which == 13) {
displayContent();
$('#figure').prepend('<img src = "http://placebear.com/100/100" />');
}
});
$('#term2').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/80/80" />');
displayContent();
}
});
$('#term3').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/50/50" />');
displayContent();
}
});
});
#content {
width: 400px;
height: 100px;
}
#figure {
position: fixed;
margin-left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="form">
<section id="fetch">
<input type="text" placeholder="Please enter your name here" id="term1" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term2" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term3" />
<button type="button" id="search">OK</button>
</section>
<section id="info">
<h4>Take a look inside with:</h4>
<section id="content">
<h5 id="name"></div>
<div id="figure"></div>
</section>
</section>
</section>
fiddle
I cleared out your code and its working now. You can give it a try.
$(document).ready(function(){
$("#info").hide();
var displayContent = function(){
$("#info").show();
var str = [],
imgs = ["http://placebear.com/100/100","http://placebear.com/101/101","http://placebear.com/102/102"];
$("#fetch input[type=text]").each(function(i){
var v = $(this).val();
if(v != ""){
str.push(v.toUpperCase());
if($("#figure").find("#image_"+i).length == 0){
$('#figure').prepend('<img src="' + imgs[i] + '" id="image_'+i+'" />');
}
}else{
$("#figure").find("#image_"+i).remove();
}
})
$("#name").html(str.join(", "));
}
$('#search').click(displayContent);
$("#fetch input[type=text]").keypress(function(event){
if(event.which == 13){
displayContent();
}
});
});
Plus your html has some problem <h5 id="name"></div> should be <h5 id="name"></h5>
Here is the fiddle https://jsfiddle.net/f9m65to6/1/
Instead of append use $("#term2").val($("#term2").val()+"newValue")

JS Constructor Function Can't Find Global Variable

The crux of this problem is that assigning a variable to an html element is not working within a constructor function.
There must be a way around this right?
The most effective way I have found is to create a method within the constructor function that returns the element.
The problematic variable is "box".
I commented out the section at the start where I tried to make box a global variable, but the constructor couldn't find the box variable. That is the weirdest part to me.
Below is my sample code:
window.onload = function()
{
document.getElementById("sub_button").onclick = adder;
document.getElementById("scrap_it").onclick = remover;
}
//var box = document.getElementById("contact_list");
//refers to the select tag containing contact names as options
var Contacts = function()
{
this.box = function (){ return document.getElementById("contact_list");}
this.list = [];
this.contact_info = document.getElementById("contact_info");
this.find = function(personName){
var found = "missing";
for(var i = 0; i < this.list.length; i++)
{
if(this.list[i].personName == personName)
{
found = i;
}
}
return found;
}
this.addPerson = function(personName, phone)
{
if (this.find(personName) == "missing")
{
personName = personName;
contact =
{
personName: personName,
phone: phone
}
this.list.push(contact);
this.update();
}
else
{
alert("Sorry, this contact name is already in use. Please choose another.");
}
}
this.update = function()
{
this.box().innerHTML = "";
for (var i = 0; i <this.list.length; i++)
{
option_element = document.createElement("OPTION");
option_node = document.createTextNode(this.list[i].personName);
option_element.appendChild(option_node);
this.box().appendChild(option_element);
}
}
this.remove = function(name_to_delete)
{
var index_to_remove = name_to_delete;
this.list.splice(index_to_remove, 1);
this.update();
}
this.postInfo = function(contact_to_display)
{
var index_to_display = contact_to_display;
alert(this.list[index_to_display].personName);
alert(this.list[index_to_display].phone);
}
}
var myList = new Contacts();
function adder()
{
myList.addPerson(document.getElementById("contact_name").value, document.getElementById("contact_phone").value);
}
function remover()
{
myList.remove(myList.box().selectedIndex);
}
function showInfo()
{
myList.postInfo(myList.box().selectedIndex);
}
And the HTML:
<html>
<head>
<title>Address Book</title>
<script type="text/javascript" src="beta3.js"></script>
</head>
<body>
<form id="contact_form">
<label for="contact_name">Name: </label>
<input type="text" id="contact_name" /><br />
<label for="contact_phone">Phone: </label>
<input type="text" id="contact_phone" /><br />
<input type="button" name="submit" value="submit" id="sub_button" />
</form>
<br />
<div>
Delete
</div>
<br />
<div>
<select name="contact_list" id="contact_list" size="10" multiple="multiple" style="width: 450px">
</select>
</div>
<div>
<textarea id="contact_info">
</textarea>
</div>
</body>
</html>
try something like this
var box;
window.onload = function()
{
document.getElementById("sub_button").onclick = adder;
document.getElementById("scrap_it").onclick = remover;
//refers to the select tag containing contact names as options
box = document.getElementById("contact_list");
}
Your code is not working because your script is executed before our element is render in dom so your box variable get nothing.

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