View page does not recognize null element in load - javascript

I have an javascript function that generates links in my page based on a DropDown. I'm checking the javascript function in two places; when the DropDown changes with attribute "onchange", and when the page is loaded. The error is generated when the page is loaded without element on viewbag, my javascript is not recognizing the null element for generate links without the information on viewbag.
<p>Pesquisar por: #Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" })
<div id="dadosFornecedor">
#if (ViewBag.CurrentFornecedor != null)
{
<fieldset>
<legend>#ViewBag.CurrentFornecedor.RazaoSocial</legend>
<b>Razão Social:</b> #ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> #ViewBag.CurrentFornecedor.Endereco
#Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor })
<input type="button" class="btn" onclick="removerFornecedor();" value="Remover Fornecedor" />
<br />
<br />
</fieldset>
<br />
}
</div>
<script type="text/javascript">
$(function () {
alteraFiltro();
});
function removerFornecedor() {
var div = $("#dadosFornecedor");
var hidden = $("#idFornecedor");
div.empty();
div.append("<input type='hidden' name='deletarFornecedor' value='true' />")
}
function alteraFiltro() {
var urlCodigo = $("#linkCodigo");
var urlLancamento = $("#linkLancamento");
var urlPagamento = $("#linkPagamento");
var urlFornecedor = $("#linkFornecedor")
var dropValue = $("#tipoPesquisa").val();
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
} else{
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
}
}
</script>

If the issue is caused by ViewBag.CurrentFornecedor not having a value when the view is first loaded, try altering your javascript along these lines:
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
// ...
}
else {
urlCodigo.attr("href", "saidasDiversassortOrder=#ViewBag.CodigoSortParm&idFornecedor="
+ #{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1}
+ "&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
// ...
}

Related

I cannot add the class "unread" to the append content of a certain data-id

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!

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

Recursive previous and next in arrow key press in custom autocomplete with jquery

I have developed customise autocomplete which works fine in terms of data pulling and displaying in the page. I want to enhance it. I want to implement something like this (multiple dataset of typeahead pluggin) where I want to select or set focus on the next and previous li of my autocomplete when down / up arrow key is pressed. Here is my jquery code which populate the autocomplete.
$("input[data-tg-autocomplete]").keyup(function (e) {
if (e.keyCode == 40 || e.keyCode == 38) {
//alert(e.keyCode);
DownUpKeyPress(e.keyCode);
}
else {
var $input = $(this);
//-----------------------------Allowing user to enter atleast one character for auto search
if ($input.val().length > 0) {
var request = $.ajax({
url: $input.attr("data-tg-autocomplete"),
method: "GET",
data: { term: $input.val() },
dataType: "json"
});
request.done(function (JsonData) {
LoadAutoSuggest(JsonData);
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
});
}
}
});
//========================populate autocomplete
function LoadAutoSuggest(result) {
var tag = "";
$('.custom-autocomplete').html("");
if (result.Destination != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Destination";
tag = tag + "</a>";
tag = tag + "</li>";
for (i = 0; i < result.Destination.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Destination' data-id='" + result.Destination[i].DestinationID + "'>";
tag = tag + "<div>";
tag = tag + result.Destination[i].DestinationName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
}
}
if (result.Business != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Business";
tag = tag + "</a>";
tag = tag + " </li>";
for (i = 0; i < result.Business.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Business' data-id='" + result.Business[i].BusinessID + "'>";
tag = tag + "<div>";
tag = tag + result.Business[i].BusinessName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
//alert(result.Business[i].BusinessName + " ID = " + result.Business[i].BusinessID)
}
}
$('.custom-autocomplete').html(tag);
$('.autocompleteListItem').click(function () {
var id = $(this).attr("data-id");
var type = $(this).attr("data-type");
var text = $(this).text();
$("#searchtext").val(text);
$('.HiddenSearchInput #id').val(id);
$('.HiddenSearchInput #type').val(type);
$('.custom-autocomplete').html("");
$('.Search-submit').trigger("click");
});
$(':not(".search-wrapper")').click(function () {
if ($('.custom-autocomplete li').length > 0) {
$('.custom-autocomplete').html("");
}
});
$('.custom-autocomplete li.list-group-item').first().addClass("focused");
}
function DownUpKeyPress(keyCode) {
//$this = $(this);
if (keyCode == 40) {
// alert('40');
// $this.next().focus();
if ($('.custom-autocomplete li').length > 0) {
var $focused = $('.custom-autocomplete li.focused');
$('.custom-autocomplete li.focused ~ .list-group-item').first().addClass('focused')
$focused.removeClass('focused')
}
return false;
} else if (keyCode == 38) {
//alert('38');
// $this.prev().focus();
if ($('.custom-autocomplete li').length > 0) {
}
return false;
}
}
and here is my html where I am populating the autocomplete
<div class="Search-container">
<span class="error search-validation"></span>
<div class="input-group input-group-lg">
<input id="searchtext" name="searchtext" type="text" class="form-control " placeholder="Find travel agents, search travel agents in your destination" data-tg-autocomplete="#Url.Action("AutocompleteBusiness")" />
<span class="input-group-btn">
<button class="btn btn-primary Search-submit" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div><!-- /input-group -->
<div class="displaynone HiddenSearchInput">
<input type="hidden" id="id" name="id" value="" />
<input type="hidden" id="type" name="type" value="" />
</div>
</div>
<ul class="list-group custom-autocomplete">
#*List will be populated from ajax call in function LoadAutoSuggest*#
</ul>
My function DownUpKeyPress is for setting focus for next and previous li. Focused li item will be used for site search but I am not been able to set focus on the next and previous li when up/down arrow is pressed. I am using MVC5 for developing my project. Probably I am wrong with jquery. May someone help me out to fix the issue. I dont want to use any pluggin for this.
Add this code in DownUpKeyPress
// for up arrow => Previous Li Focus
if (keyCode == 40) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').next('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').first().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').next('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').addClass('focused');
}
}
return false;
}
// for down arrow => Next Li Focus
else if (keyCode == 38) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').prev('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').last().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').prev('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').addClass('focused');
}
}
return false;
}

Jquery insert values of text-field into list-box.?

I want to fetch value from the textfield and add to the listbox.
Here is my jquery code
JS:-
{
$('#btn_AddToList').click(function(
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if('' != region)
{
var newOption = document.createElement('option');
newOption.text = region;
newOption.value = region;
if($.browser.msie)
{
select.add(newOption);
}
else
{
select.add(newOption, null);
}
}
return false;
});
});
here is my html code
html:
<input type="text" name="region" id="txt_RegionName" /><br />
<input type="button" name="add" id="btn_AddToList" value="add" class="btn btn-success" /></br />
<select size="10" id="lst_Regions" style="width: 500px;">
</select>
question: I cannot add the value of the txt_RegionName to the lst_Region ,where i am going wrong?
Thank you.
$('#btn_AddToList').click(function () {
var val = $('#txt_RegionName').val();
$('#lst_Regions').append('<option>' + val + '</option>');
$('#txt_RegionName').val('').focus();
})
jsFiddle example
you can do this like:
$('#btn_AddToList').click(function(event)
{
var region = $('#txt_RegionName').val();
if(region && !$('#lst_Regions>option[value=' + region + ']').length){
var newOption = $('<option value="' + region + '">' + region + '</option>');
$('#lst_Regions').append(newOption);
}
//return false;
event.preventDefault();
event.stopPropagation();
});
just to let you know, you can prevent it from duplicate values using:
$('#lst_Regions>option[value=' + region + ']').length
which has to be zero, and as you see I have added that to my answer.
{
$('#btn_AddToList').click(function()
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if ('' != region) {
$(document.createElement('option')).text(region).val(region).appendTo(select);
}
return false;
});
};

Need help debugging a Javascript code and/or getting it to work

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');
.........................
}

Categories

Resources