object array not returning values - javascript

I am working on an assignment that I feel like I am very close to finishing, but something is going wrong. When I try to print each employee to the table at the end, nothing happens. my array for the "new employee" is returning an empty array.
please help explain your code if you correct mine. it is a little bit of a long code, but i appreciate the help! everything was working until i added the deptSearch stuff, and everything underneath it.
i left out the removeChildren() and selectedValue() because they were pre-coded for me and they work with no issue
lastly, the only code i was supposed to write for this assignment is within the eventListener ("click") function
/* Constructor function for the employee class */
function employee(id, firstName, lastName, dept, position, email, phone, photo) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dept = dept;
this.position = position;
this.email = email;
this.phone = phone;
this.photo = photo;
}
/* Object literal for search results */
var searchResult = {
employees : [],
sortById : function() {
this.employees.sort(function(a,b) {
if (a.id < b.id) {return -1;}
else {return 1;}
});
}
};
/* Event listener to retrieve and display employee records matching the search condition */
document.getElementById("searchButton").addEventListener("click", function() {
var tableBody = document.querySelector("table#staffTable tbody");
var tableCaption = document.querySelector("table#staffTable caption");
tableBody.removeChildren();
searchResult.employees = [];
staff.directory.forEach(function (record){
var nameSearch = document.getElementById("nameSearch").value;
var nameSearchType = document.getElementById("nameSearchType").selectedValue();
var positionSearch = document.getElementById("positionSearch").value;
var positionSearchType = document.getElementById("positionSearchType").selectedValue();
var deptSearch = document.getElementById("deptSearch").selectedValue();
// nameSearch switch
switch (nameSearchType) {
case "contains":
var nameRegExp = new RegExp(nameSearch, 'i');
break;
case "beginsWith":
var nameRegExp = new RegExp('^' + nameSearch, 'i');
break;
case "exact":
var nameRegExp = new RegExp('^' + nameSearch + '$', 'i');
break;
} // end of nameSearch switch
var foundName = nameRegExp.test((record.lastName));
// positionSearch switch
switch (positionSearchType) {
case "contains":
var positionRegExp = new RegExp(positionSearch, 'i');
break;
case "beginsWith":
var positionRegExp = new RegExp('^' + positionSearch, 'i');
break;
case "exact":
var positionRegExp = new RegExp('^' + positionSearch + '$', 'i');
break;
} // end of positionSearch switch
var foundPosition = positionRegExp.test((record.position));
// deptSearch if statement
if (deptSearch == "" || deptSearch == record.dept.valueOf()) {
var foundDept = true;
}
if (foundName && foundPosition && foundDept) {
searchResult.employees.push(new employee(record.id, record.firstName, record.lastName, record.dept, record.position, record.email, record.phone, record.photo));
}
console.log(searchResult.employees);
});
tableCaption.textContent = searchResult.employees.length + " records found";
searchResult.sortById();
searchResult.employees.forEach(function () {
tableBody.innerHTML += "<tr>\
<td><img src=" + searchResult.employees.employee.photo + " /></td>\
<td>" + searchResult.employees.firstName + " " + searchResult.employees.lastName + "</td>\
<td>" + searchResult.employees.dept + "</td>\
<td>" + searchResult.employees.position + "</td>\
<td><a href='mailto:" + searchResult.employees.email + "'>" + searchResult.employees.email + "</a></td>\
<td><a href='tel:" + searchResult.employees.phone + "'>" + searchResult.employees.phone + "</a></td>\
</tr>"
});
});

Related

Remove() function doesnt work in firebase for web

This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>

How do I remove just the current instance of the array, not all instances of the array?

How do I remove just the current instance of the array, not all instances of the array?
var persons = [];
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
Created new node instances.
for (var l in persons) {
var listNode = document.createElement("LI");
var btn = document.createElement("BUTTON");
btn.innerHTML = "Remove";
showList.appendChild(listNode);
showList.appendChild(btn);
Displays pushed instances correctly.
listNode.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>'
}
Tried a few variations of the following function but just empties the array, or at least wont return the amended array.
btn.onclick = function() {
var index = Array.indexOf(persons[l]);
persons.splice(index, 1);
return persons;
}
if (showAllButton.value=="Show Contacts") {
showAllButton.value = "Hide Contacts";
showList.style.display = "block";
}
else if (showAllButton.value = "Hide Contacts") {
showAllButton.value = "Show Contacts";
showList.style.display = "none";
}
}
probably bind l, remove the element at index l, then redraw the dom somehow.:
btn.onclick = function(l) { //take over the bound l
persons.splice(l, 1);
//some kind of redraw
showAllButton.click();
}.bind(null,l);//bind l
Something like this should work as expected (sorry, blind coding, have no time to test now)
var persons = [];
function removePerson(index) {
persons.splice(index, 1);
renderList();
}
function clearList() {
while (showList.firstChild) {
showList.removeChild(showList.firstChild);
}
}
function renderItem(person, index) {
var item = showList.appendChild(document.createElement("LI"));
var label = item.appendChild(document.createElement("SPAN"));
label.innerHTML = persons[i];
var btn = item.appendChild(document.createElement("BUTTON"));
btn.innerHRML = "Remove";
btn.onclick = removePerson.bind(null, index);
}
function renderList() {
clearList();
persons.forEach(renderItem);
}
Not a kind of best practices, but seems to be working.
Final Working Code, thank you!
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
for (var l in persons) {
var list = showList.appendChild(document.createElement("LI"));
list.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>';
var btn = showList.appendChild(document.createElement("BUTTON"));
btn.innerHTML = "Remove";
btn.onclick = function(l) {
persons.splice(l, 1);
showAllButton.click();
}.bind(null,l);
}

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

Firefox thinks <fieldset> is a form element; Chrome doesn't

In my JavaScript program, I get values from a form through its elements and then print them in order, in an alert. This works fine in Firefox, but in Chrome the order is wacky and it ends with the "Submit" button.
I tried getting rid of the fieldset and adjusting the numbers, and it worked, but I liked the fieldset! Also, I can't just make an array and iterate through it because the fields are tab-order adjusted and I want to print them accordingly. Any suggestions?
Upon trying to validate I found that I do indeed need the fieldset for XHTML Strict. I've been storing the elements in an array, like so:
var $ = function (id) { return document.getElementById(id); }
function check() {
var x = $("myForm");
var user = new Array();
user[0] = x.elements[0].value;
user[1] = x.elements[2].value;
user[2] = x.elements[4].value;
user[3] = x.elements[1].value;
user[4] = x.elements[3].value;
user[5] = x.elements[5].value;
And then checking them using another couple of arrays and displaying the results in a pop-up:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
if (user[i] == "") {
display[i] = "You entered nothing.";
}
else if (user[i] == answers[i]) {
display[i] = "Correct!";
}
else {
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
}
WebKit bug (https://bugs.webkit.org/show_bug.cgi?id=48193).
I think you'll be better off using IDs:
<form ...>
<input ... id="q0" />
<input ... id="q1" />
<input ... id="q2" />
</form>
So you can write this JavaScript code:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display[i] = "You entered nothing.";
else if (user == answers[i])
display[i] = "Correct!";
else
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
Your code can receive a lot of improvement, too:
var answers = [ "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" ];
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display.push( "You entered nothing." );
else if (user == answers[i])
display.push( "Correct!" );
else
display.push ( "Wrong. The correct answer is \"" + answers[i] + "\"." );
}
alert(display.join('\n'));

Categories