This is all my code I hope you can see where I'm going wrong.
var $randomnumber1;
var $randomnumber2;
var $answer;
var $counter = 1;
var $data;
function start_game() {
document.getElementById('counternumber').innerHTML = $counter;
document.getElementById('txtbox').value = "";
$randomnumber1 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
$answer = $randomnumber1 + $randomnumber2;
$counter++;
setFocus();
}
function check_answer() {
var $txt = document.getElementById('txtbox');
var $value = $txt.value;
if ($value == $answer) {
alert('You are correct');
}
else {
alert('You are incorrect, the answer was ' + $answer);
}
document.getElementById('txtbox').value = "";
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
$randomnumber1 = Math.floor(Math.random()*11);
$randomnumber2 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
document.getElementById('num2').innerHTML = $randomnumber2;
$answer = $randomnumber1 + $randomnumber2;
document.getElementById('counternumber').innerHTML = $counter;
$counter++;
if ($counter > 4) {
alert ('End of game......Thanks for playing');
$counter = 1;
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
}
function addAnswers() {
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
<div class="container" id="wrapper">
<h3>Games Played = <b id='counternumber'></b> / 3 </h3>
<div id="total">Total: <p id="sumtotal"></p></div>
<div class="left"><h3 id="num1"></h3></div>
<div class="plus"><img src="images/plus.png"></div>
<div class="right"><h3 id="num2"></h3></div>
<button onclick="start_game(); myCountDown()">Start Game</button>
<form id="form">
<input type="text" id="txtbox" />
<input type="button" value="Answer" onclick="check_answer(); setFocus(); ShowResults(); sumResults()" />
</form>
</div>
home page
</div> <!-- /content -->
<div id="aside">
</div>
You could use this:
function addAnswers()
{
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
Your question is unclear, but this should be something along the lines of what you're looking for. What you have to do is add a <ul> with the id of ans and this function will append li components to it (your answers) every time you run it. The answer itself will be stored into data.
Try it - if you want help customizing it, please update your answer.
Related
I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!
I have used following code to develop sentence grammar practice. When I click button then order should to maintained. I want it when button clicked then it should hide but after click on top button again show up.
Move sentence to left if there is blank. Also show button again if words clicked again.
Should using only buttons for showing at top also at bottom?
<html>
<head>
<title>
</title>
</head>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for(i=0;i<senArr.length;i++)
{
//alert(senArr[i]);
dashElement += "<div onclick='funDiv(this.id);' style='display: inline'" + "id = dashid" + i + ">" + '__ ' + '</div>';
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
//var dashID = document.getElementById("dashid0").innerHTML;
//var dash1 = document.getElementById("val");
//dash1.innerHTML= dashID;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='fun(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var ii = 0;
function funDiv(clicked){
//alert(clicked);
var inText = document.getElementById(clicked).innerHTML;
document.getElementById(clicked).innerHTML = " __ " ;
ii--;
}
function fun(clicked){
//alert(clicked);
document.getElementById(clicked).style.display = "none";
document.getElementById("dashid" + ii).innerHTML = document.getElementById(clicked).innerHTML + " ";
//document.getElementById(clicked).remove();
ii++;
}
</script>
</script>
</body>
</html>
How about something like this?
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for (var i = 0; i < senArr.length; i++) {
dashElement += `<div onclick='dashClick(this.id);' style='display: inline' id=dash${i}> __ </div>`;
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var picked = 0;
function dashClick(clicked) {
const dash = document.getElementById(clicked);
dash.innerHTML = " __ ";
const btn = document.getElementById(`btn${dash.btnId}`);
btn.style.display = "inline";
picked--;
}
function btnClick(clicked) {
var btnId = clicked.replace('btn', '');
document.getElementById(clicked).style.display = "none";
const dash = document.getElementById("dash" + picked)
dash.innerHTML = document.getElementById(clicked).innerHTML + " ";
dash.btnId = btnId;
picked++;
}
</script>
</body>
</html>
I have implemented it using appendChild and remove functions of JavaScript.
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
var btnElements = "";
for (var i = 0; i < senArr.length; i++) {
btnElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'> " + senArr[i] + ' </button>';
}
var container = document.getElementById("container");
container.innerHTML = btnElements;
var picked = 0;
function dashClick(clicked) {
//console.log(clicked);
var buttons = document.getElementsByTagName('button');
var dash = document.getElementById("dash");
dashChild = dash.childNodes;
console.log(document.getElementById(clicked).innerText);
for(i=0;i<senArr.length;i++){
if(document.getElementById(clicked).innerText.trim() == buttons[i].innerText.trim()){
//console.log("Match");
buttons[i].style.opacity = "1";
buttons[i].style.pointerEvents = "auto";
}
}
document.getElementById(clicked).remove(); // remove clicked text
}
// Button click
function btnClick(clicked) {
var dashElement = document.createElement("div");
var text = document.getElementById(clicked).innerText;
dashElement.style.display = "inline";
dashElement.innerHTML = "<div style='display: inline' onclick='dashClick(this.id);' id=" + picked +"> " + text + " </div>"; // add text at top of button
document.getElementById("dash").appendChild(dashElement);
picked++;
document.getElementById(clicked).style.opacity = "0"; //hide button that has been clicked
document.getElementById(clicked).style.pointerEvents = "none";
}
</script>
</body>
</html>
So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}
this is my code...
How get the textbox array value to store in database...
<html>
<head>
<script type="text/javascript">
var max = 4; //highest number to go to
var currentIndex = 0;
function btnClick() {
if(currentIndex < max){
currentIndex++;
postClick();
}
}
function Previous(){
if(currentIndex>0){
currentIndex--;
postClick();
}
}
function postClick() {//whatever you want to happen goes here
var sahans = new Array();
sahans[currentIndex] == d;
var d = document.getElementById("div");
d.innerHTML = "<p><input type='text' name='name"+currentIndex+"[]'>";
d.innerHTML += "<p><input type='text' name='topic"+currentIndex+"[]'>";
document.getElementById("div").style.display = "";
}
</script>
</head>
<body>
<form id="form1">
<div>
<input type="button" value="Previous" onclick="Previous();" />
<input type="button" value="Next" onclick="btnClick();" />
<div id="div"></div>
</div>
</form>
</body>
</html>
JavaScript:
function store(form) {
var input = form.getElementsByTagName('input');
var myarray = Array();
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text') {
myarray[input[i].getAttribute('name')] = input[i].value;
}
}
for (var i in myarray) {
alert(i + ': ' + myarray[i]);
}
}
HTML:
<form onsubmit="store(this); return false">
<p>
<input type="text" name="name" /><br />
<input type="text" name="topic" />
</p>
<p>
<input type="submit" value="Store in database" />
</p>
</form>
Edit:
Ok, now I made a full example with AJAX and the actual saving to the database. The AJAX call uses 'POST'. Simply fill in the number of fields that you want in the max variable.
JavaScript:
var max = 10;
var current = 0;
function goto(form, pos) {
current += pos;
form.prev.disabled = current <= 0;
form.next.disabled = current >= max - 1;
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
function store(form) {
var input = form.getElementsByTagName('input');
var data = '';
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text')
data += '&' + input[i].getAttribute('name') + '=' + input[i].value;
}
data = encodeURI('n=' + max + data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('POST', 'store.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.setRequestHeader('Connection', 'close');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != '')
alert(this.responseText);
else {
form.submit.value = 'Saved!';
setTimeout(function() { form.submit.value = 'Save to database' }, 500);
}
}
}
xhr.send(data);
}
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('div')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset><legend>Entry ' + (i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
HTML:
<form action="submit.php" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<div>
<noscript>Please enable JavaScript to see this form correctly.</noscript>
</div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
Users who have JS disabled will see what's in the <noscript> tag, otherwise it's replaced with the fieldsets. Also it's good to make an alternative submit page (submit.php) for users who have JS disabled. Below is store.php, the AJAX submit script.
PHP (store.php):
<?php
if (empty($_POST['n']) || $_POST['n'] < 1) die('Invalid request!');
$fields = array('name', 'topic');
$errors = '';
for ($i = 0; $i < $_POST['n']; $i++) {
foreach ($fields as $field) {
if (empty($_POST[$field . $i]))
$errors .= '- ' . $field . ' ' . ($i + 1) . "\n";
}
}
if ($errors != '')
die("Please fill in the following fields:\n" . $errors);
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb', $db);
for ($i = 0; $i < $_POST['n']; $i++) {
$name = mysql_real_escape_string($_POST['name' . $i]);
$topic = mysql_real_escape_string($_POST['topic' . $i]);
mysql_query(' INSERT INTO entries (id, name, topic) VALUES (' . $i . ', "' . $name . '", "' . $topic . '")
ON DUPLICATE KEY UPDATE name = "' . $name . '", topic = "' . $topic . '"
') or die('Database error!');
}
mysql_close($db);
?>
The output text of this script (if there is an error) is displayed in the JavaScript alert.
I hope it's working for you now.
This would be help ful for you
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<script type="text/javascript">
function validateText(event){
var tar_ele = $(event.target);
if(tar_ele.val() is not valid)
tar_ele.focus();
}
</script>
<input type="text" name="Tue[]" onblur="validateText(event)"/>
javascript text box array and get values and focus on particular field
Been pulling my hair out since the past 4 hours. I have two Javascript file, both works completely fine by itself. One is use as a login verification, the other takes my registration page and writes the form to an XML file.
When I took some code from my login JS and place it in my registration JS, my registration JS doesn't even function properly. I'm thinking my issue is probably the placement of my codes.
If I post the complete codes here, the post would be like 10ft long, so here's all my files:
http://www.mediafire.com/?wt9bchq35pdqxgf
By the way, this is not a real world application, it's just something I'm doing.
Here's my original Javascript file for the registration page:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\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('></Person>\n');
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
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()
This code here will write to my XML file after I hit the submit button. And this is how the XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" PersonID="111" FirstName="Bob" LastName="Smith" Gender="M" DOB="01/01/1960" Title="Hello1" ></Person>
<Person Usrname="Joe222" Pswd="Johnson222" PersonID="222" FirstName="Joe" LastName="Johnson" Gender="M" DOB="12/01/1980" Title="Hello2" ></Person>
<Person Usrname="Tracey333" Pswd="Wilson333" PersonID="333" FirstName="Tracey" LastName="Wilson" Gender="F" DOB="12/01/1985" Title="Hello3" ></Person>
<Person Usrname="Connie444" Pswd="Yuiy444" PersonID="444" FirstName="Connie" LastName="Yuiy" Gender="F" DOB="12/01/1985" Title="Hello4" ></Person>
<Person Usrname="Brian555" Pswd="Dame555" PersonID="555" FirstName="Brian" LastName="Dame" Gender="M" DOB="12/01/1985" Title="Hello5" ></Person>
<Person Usrname="Scott666" Pswd="Bikes666" PersonID="666" FirstName="Scott" LastName="Bikes" Gender="MF" DOB="12/01/1985" Title="Hello6" ></Person>
<Person Usrname="sadsa" Pswd="s" PersonID="s" FirstName="s" LastName="s" Gender="s" DOB="s" Title="s" ></Person>
If I modify my code to what is shown below, the XML file won't even create. Nor will the authentication run properly. As in the the box won't turn red and no alert message pops up. But the codes I add in does work on my other JS file for my log in page.
Here's the edited registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\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
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
var errmsg = "empty field";
var errmsg2 = "You have register successfully";
var msg = "This user name is already in use"; //this is what I added
var errCount = 0;
errCount += LogInVal(usrn);
errCount += LogInVal(pswd);
errCount += LogInVal(pid);
errCount += LogInVal(fname);
errCount += LogInVal(lname); //this is what I added
errCount += LogInVal(gender);
errCount += LogInVal(dob);
errCount += LogInVal(title);
if (errCount != 0) //the if/else statements are what I added
{
file.WriteLine('</PersonInfo>\n'); //checks to see if textbox is empty, if yes, alert
file.Close();
alert(errmsg);
return false;
}
else if(authentication(usrn) == true)
{
file.WriteLine('</PersonInfo>\n'); //checks to see if user name entered is already in use
file.Close();
alert(msg);
return false;
}
else
{
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" '); //this block of code here was there originally
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" '); //previous two condition is false, registration successful, writes to XML.
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
alert(errmsg2);
return true;
}
} // end SaveXML function --------------------
function authentication(usrname1) //function was added
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrn)
{
return true;
}
}
return false;
}
function LogInVal(objtxt) //function was added
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
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()
Here's the login page JS, which contains the code(it works fine in this file) that was added to the registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
{
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"));
arrPerson.push(tmpArr);
x++;
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
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)
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
function authentication(usrname1, pswd1)
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrname1 && pswd1 == arrPerson[x][1])
{
return true;
}
}
return false;
}
function setCookie(Cookiename,CookieValue)
{
alert('executing setCookie');
document.cookie = Cookiename + '=' + CookieValue;
}
Here's my registration HTML page:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="return initialize_array()">
Username:<input type="text" name="Usrn" id="Usrn" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="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>
Hope I'm not being too confusing.
What I see in the code is this:
create XML file, start with <personInfo>
if error, skip </personInfo>
now add something else.
so you're not closing the XML element. Of course it won't create the file. It won't write invalid XML, and that's "expected" behavior.
You can also debug your jvascript code to enable javascript debugging. go to : tools > intenet options > advanced > browsing and uncheck (disable script debugging). in Internet Explorer Browser . then you can attach debugger by writing debugger; # any location in javascript function egs:
function SaveXML(UserData)
{
debugger;
var file = fso.CreateTextFile(FILENAME, true); file.WriteLine('\n');
file.WriteLine('\n');
.........................
}