alert 2 arrays in same line javascript - javascript

I have a problem alerting out 2 arrays on same line in Javascript. The user should write Movie name and movie rating(1-5) 5 times, and printMovies() function should print out users (movie)name and (movie)rating in a single line something like this:
Movie Rating
Star Wars 5
Lord of the Rings 4
Casino 4
Movie4 3
Movie5 2
How do I alert out all of five inputs in a single line (movie + rating) per line, AFTER they have got input from user?
//CODE
var title;
var rating;
var a = [];
var movies = [];
var ratings = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
}
function addMovie(title, rating) {
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title);//Pushing title to movies
a.push(movies);//Pushing movies to a array
ratings.push(rating);//Pushing rating to ratings
a.push(ratings);//Pushing ratings to a array
printMovies()
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[0][0] + " " + a[0][1]);//Here is my biggest problem!
}
}

You problem is in the addMovie function your push the array to array. that means structure of the a is
a = [['title'] , ['rating'] , ['title','title1'],['rating',ratting1],......]
Try this with json object.
var movies = [];
function addMovie(title, rating) {
var movie = {};
do {
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movie.title = title;
movie.ratings = rating; movies.push(movie);
}
function printMovies() {
for (var i = 0; i < movies.length; i++) {
alert(movies[i].title + " " + movies[i].ratings);
}
}
function buttonAddMovie()//Button onclick
{
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
printMovies();
}

<html>
<head>
<script>
var arr = [{
"Movie": "Movie1",
"Rating": 1
}, {
"Movie": "Movie2",
"Rating": 2
}, {
"Movie": "Movie3",
"Rating": 2
}, {
"Movie": "Movie5",
"Rating": 4
}, {
"Movie": "Movie4",
"Rating": 5
}, ];
var str = "";
for (var i = 0; i < arr.length; i++) {
str += "Movie Name: " + arr[i].Movie + " || Rating: " + arr[i].Rating + "\n";
}
alert( "Json Iterated Output \n" + str);
</script>
</head>
</html>

The reason it wasn't working was you had an array, a.
You pushed the movie name to 'a'
a = ['Movie name'];
But then you pushed the rating to 'a' separately
a = ['Rating'];
So the movie's name was replaced with rating, hence the alerts saying '(movie's name) undefined', then '(movie's rating) undefined'.
What I've done is removed the rating array and pushed the movie name and rating at the same time.
Also, I've changed the for loop to display the current movie by changing
alert(a[0][0] + " " + a[0][1]);
to
alert(a[i][0] + " " + a[i][1]);
otherwise it will always display the first movie rating.
var title;
var rating;
var a = [];
var movies = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating, document.getElementById('quantity').value)
}
function addMovie(title, rating, amount) {
for(var count = 0; count < amount; count++){
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title,rating);//Pushing title to movies
a.push(movies);//Pushing movies to a array
movies = [];
}
printMovies();
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[i][0] + " " + a[i][1]);
document.getElementById('movielist').innerHTML+= "<li>"+a[i][0]+" - "+a[i][1]+"</li>"; // Adds movies to the <ul>
}
}
<h2>Add</h2>
<input id='quantity' placeholder='Amount of movies you want to add' /><br>
<button onclick='buttonAddMovie();'>Add Movies</button>
<h2>Movie list</h2>
<ul id='movielist'></ul>
Now you can stack as many as you want by writing the number in the input tag.
The movies are then displayed at the end in an unformatted list.
Very basic code, but I hope it helps.

Related

Student Object Program Errors

I have a program that is suppose to ask the user for their ID, First Name, Last Name, select a Rank (grade level), and the GPA. After all fields go through error checking, the data should then be put into an object called student. Next the student object should be pushed to the Summary Array. Displaying the first and last name, next line ID, next line Class Rank, next line GPA.
UPDATE CURRENTLY: all error checking (if/elses) works! Secondly, only the "--------" happens when Add Student is pressed besides the error checking.
Full Code:
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
studentID = document.getElementById('Text1').value;
studentFirst = document.getElementById('Text2').value;
studentLast = document.getElementById('Text3').value;
Rank = document.getElementById('Select1').value;
studentGPA = document.getElementById('Text4').value;
if (!studentList.includes(studentID)) {
if (studentID != '') {
if (studentFirst != '') {
if (studentLast != '') {
if (Rank != -1) {
if (studentGPA != '') {
if (studentGPA > 0 && studentGPA < 4) {
var Student = {
studentID: document.getElementById('Text1').value,
studentFirst: document.getElementById('Text2').value,
studentLast: document.getElementById('Text3').value,
Rank: document.getElementById('Select1').value,
studentGPA: document.getElementById('Text4').value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>"
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option value="-1">(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
You need to initialize Summary to an empty array. Otherwise, Summary.push() gets an error because you can't push onto undefined.
The index of the prompt option in the Rank menu is 0, not 1, so you should check for that in the validation.
The Create() function reassigns all the variables that contain the input elements, replacing them with their values. You should use different variables, or just use the .value properties of the global variables.
You need to convert the value of Rank to a number before comparing with numbers.
You're missing a + at the end of the first line of the string you're appending to the DIV, so you're only adding the ---- line.
When checking for duplicates, you need to compare studentID.value with the studentID property of the array element, not the whole array element. And you should be searching Summary, not studentList.
var studentList = []
var studentID;
var studentFirst;
var studentLast;
var Rank;
var studentGPA;
var Summary = [];
studentID = document.querySelector("#Text1");
studentFirst = document.querySelector("#Text2");
studentLast = document.querySelector("#Text3");
Rank = document.querySelector("#Select1");
studentGPA = document.querySelector("#Text4");
function AddListeners() {
studentID.addEventListener("mouseenter", ChangeColor1);
studentID.addEventListener("mouseleave", ChangeColorBack1);
studentFirst.addEventListener("mouseenter", ChangeColor2);
studentFirst.addEventListener("mouseleave", ChangeColorBack2);
studentLast.addEventListener("mouseenter", ChangeColor3);
studentLast.addEventListener("mouseleave", ChangeColorBack3);
Rank.addEventListener("mouseenter", ChangeColor4);
Rank.addEventListener("mouseleave", ChangeColorBack4);
studentGPA.addEventListener("mouseenter", ChangeColor5);
studentGPA.addEventListener("mouseleave", ChangeColorBack5);
studentGPA.addEventListener("keypress", ShowKey);
}
function ChangeColor1() {
studentID.style.backgroundColor = "yellow";
}
function ChangeColorBack1() {
studentID.style.backgroundColor = "";
}
function ChangeColor2() {
studentFirst.style.backgroundColor = "yellow";
}
function ChangeColorBack2() {
studentFirst.style.backgroundColor = "";
}
function ChangeColor3() {
studentLast.style.backgroundColor = "yellow";
}
function ChangeColorBack3() {
studentLast.style.backgroundColor = "";
}
function ChangeColor4() {
Rank.style.backgroundColor = "yellow";
}
function ChangeColorBack4() {
Rank.style.backgroundColor = "";
}
function ChangeColor5() {
studentGPA.style.backgroundColor = "yellow";
}
function ChangeColorBack5() {
studentGPA.style.backgroundColor = "";
}
function ShowKey(e) {
if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 46) {
e.preventDefault();
}
}
function Create() {
if (!Summary.find(s => s.studentID == studentID.value)) {
if (studentID.value != '') {
if (studentFirst.value != '') {
if (studentLast.value != '') {
if (Rank.selectedIndex != 0) {
if (studentGPA.value != '') {
let GPAVal = parseFloat(studentGPA.value);
if (GPAVal > 0 && GPAVal < 4) {
var Student = {
studentID: studentID.value,
studentFirst: studentFirst.value,
studentLast: studentLast.value,
Rank: Rank.value,
studentGPA: studentGPA.value,
};
Summary.push(Student);
document.getElementById("studentinfo").innerHTML = "";
for (var i = 0; i < Summary.length; i++) {
document.getElementById("studentinfo").innerHTML +=
"------------------------------------------------------" + "<br/>" +
"Name: " + Summary[i].studentFirst + " " + Summary[i].studentLast + "<br/>" +
"ID: " + Summary[i].studentID + "<br/>" +
"Class: " + Summary[i].Rank + "<br/>" +
"GPA: " + Summary[i].studentGPA + "<br/>";
}
} else
alert("GPA must be between 0 and 4");
} else
alert("GPA is blank");
} else
alert("Rank has not been selected");
} else
alert("Last Name is blank");
} else
alert("First Name is blank");
} else
alert("Student ID is blank");
} else
alert("Duplicate Student ID");
}
<body onload="AddListeners()">
ID:<input id="Text1" type="text" />
<br> First Name:<input id="Text2" type="text" />
<br> Last Name:<input id="Text3" type="text" />
<br>
<select id="Select1">
<option>(Select a Rank)</option>
<option>Freshmen</option>
<option>Sophomore</option>
<option>Junior</option>
<option>Senior</option>
</select>
<br> GPA:
<input id="Text4" type="text" />
<br>
<input id="Button1" type="button" value="Add Student" onclick="Create()" />
<br> All added students today:
<br>
<div id="studentinfo"></div>
<br>
</body>
Rank has no selectedIndex because Rank is not an element or node.
Rank = document.getElementById('Select1').value;
You should set the value attribute on your option tags.
<option value="-1">(Select a Rank)</option>
if (Rank != -1) {

When I clear it and add another item to my shopping cart, the item that I cleared come again

This is the code I used for my shopping cart. When I use this code the problem is that when I click the clear button, and then I add another item, the previous Item that I cleared came back
I have tried to move around the saveCart function so it will properly do its job, but there are still no progress in solving the problem
This is the buttons to buy the Item ( I only show the button since probably the effect is only at here )
<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Avocado & Brownie Cake" data-price="150000">
<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Strawberry & Watermelon Cake" data-price="65000">
This is the space to show the items and the clear button
<table id="show-cart">
<br>
</table>
<br>
<button id="clear-cart" onClick="clearCart()">Clear Cart</button>
This is the JQuery ( I use JQuery 3.3.1.min )
$(".add-to-cart").click(function(event){
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
addItemToCart(name, price, 1);
displayCart();
});
function displayCart(){
var cartArray = listCart();
var output ="";
for (var i in cartArray){
output +=
"<tr>"
+"<td class='itemName'>"
+cartArray[i].name
+"</td>"
+"<td class='itemPrice'>"
+"Rp "
+cartArray[i].price
+"</td>"
+"<td>"
+" "
+"</td>"
+"<td class='itemCount'>"
+cartArray[i].count
+"</td>"
+"<td style='width:20px;'>"
+"</td>"
+"<td>"
+"<span class='sub-item' data-name='"+cartArray[i].name+"'>-</span>"
+"</td>"
+"<td style='width:12px;'>"
+"</td>"
+"<td>"
+"<span class='delete-item' data-name='"+cartArray[i].name+"'>×</span>"
+"</td>"
+"</tr>"
}
$("#show-cart").html(output);
$("#total-cart").html( totalCart() );
$("#cart-count").html( countCart() );
saveCart();
}
$("#show-cart").on("click", ".delete-item", function(event) {
var name = $(this).attr("data-name");
removeItemFromCartAll(name);
displayCart();
});
$("#show-cart").on("click", ".sub-item", function(event) {
var name = $(this).attr("data-name");
removeItemFromCart(name);
displayCart();
});
This is the Javascript
var cart = [];
var Item = function(name, price, count){
this.name = name;
this.price = price;
this.count = count;
}
// adding item to cart
function addItemToCart(name, price, count) {
for (var i in cart) {
if (cart[i].name === name ) {
cart[i].count += count;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
}
// Removes 1 Item From Cart
function removeItemFromCart(name){
for (var i in cart) {
if (cart[i].name === name){
cart[i].count --;
if (cart[i].count === 0){
cart.splice(i, 1)
}
break;
}
}
saveCart();
}
// Clear 1 Object From Cart
function removeItemFromCartAll(name){
for (var i in cart) {
if (cart[i].name === name){
cart.splice(i,1);
break;
}
}
saveCart();
}
// Clear The Cart
function clearCart(){
cart = [];
document.getElementById("show-cart").innerHTML = "";
saveCart();
document.getElementById("total-cart").innerHTML = "0";
}
// Shows Total Count Of Item
function countCart(){
var totalCount = 0;
for (var i in cart){
totalCount += cart[i].count;
}
return totalCount;
}
// Shows Total Price
function totalCart(){
var totalCost = 0;
for (var i in cart){
totalCost += cart[i].price * cart[i].count
}
return totalCost;
saveCart();
}
// Returns an array
function listCart(){
var cartCopy = [];
for (var i in cart){
var item = cart[i];
var itemCopy = {};
for (var p in item){
itemCopy[p] = item[p];
}
cartCopy.push(itemCopy);
}
return cartCopy;
}
function saveCart(){
localStorage.setItem("shoppingCart", JSON.stringify(cart));
}
function loadCart(){
cart = JSON.parse(localStorage.getItem("shoppingCart"));
}
loadCart();
displayCart();
I expected the output that when the clear button is clicked, and I add an item, the item shown is only 1 and the previous item in the cart before I clicked is gone.
Sorry, I can not read your code, there is too much to say, and I guess your mistake comes from bad management on the addressing of tables and their elements.
I adapted one of my old code to match it to your work; this is a big technical gap for you, but I think it will be useful for you to program on better rails :)
HTML part:
`
<div id="Bt_BUY">
<button data-price="150000" >Avocado & Brownie Cake</button>
<button data-price="65000" >Strawberry & Watermelon Cake</button>
</div>
<table id="show-cart">
<thead>
<tr>
<th>name</th>
<th>price</th>
<th>count</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id="clear-cart" >Clear Cart</button>
`
JS part
`
"use strict"
const Buy_obj = {
List : [],
DisplayTable : null,
add( x_name, x_price, x_count ) {
let idx = this.List.findIndex( e=>e.name=== x_name);
if (idx>=0)
{ this.List[idx].count += x_count; }
else
{ this.List.push( { 'name' : x_name, 'price' : x_price, 'count' : x_count } ) }
this.saveList();
this.drawTable();
}
,
clear(){
this.List.length = 0;
this.saveList();
this.drawTable();
}
,
remove( x_name ) {
let idx = this.List.findIndex( e=>e.name=== x_name);
if (idx>=0) {
this.List[idx].count--;
if (this.List[idx].count <= 0)
{ this.List.splice(idx,1) }
}
this.saveList();
this.drawTable();
}
,
saveList() {
localStorage.setItem("shoppingCart", JSON.stringify(this.List));
}
,
loadList() {
let ls_list = localStorage.getItem("shoppingCart");
if ( ls_list)
{ this.List = JSON.parse(ls_list); }
}
,
initialise( $xTable ) {
this.DisplayTable = $xTable;
this.loadList();
this.drawTable();
}
,
drawTable() {
this.DisplayTable.innerHTML = "";
this.List.forEach(e=>{
let
T_row = this.DisplayTable.insertRow(-1),
T_cell_0 = T_row.insertCell(0),
T_cell_1 = T_row.insertCell(1),
T_cell_2 = T_row.insertCell(2);
T_cell_0.textContent = e.name;
T_cell_1.textContent = e.price;
T_cell_2.textContent = e.count;
})
}
}
// *************************** Main *****************************
Buy_obj.initialise ( document.querySelector('#show-cart tbody') );
document.querySelector('#Bt_BUY').onclick = function(e) {
if (!e.target.matches('button')) return;
e.stopPropagation();
Buy_obj.add( e.target.textContent, e.target.dataset.price, 1 );
}
document.querySelector('#clear-cart').onclick = function(e) {
Buy_obj.clear();
}
`

Javascript Alert when no matching results from search query

I created a Chicago employee search index and wanted to create an alert when there are no matching records found, but can't seem to be able to find out what value I need to put in for when it's empty. Ideally, when the function get's submitted and no results are found, it would push an alert onto the screen indicating no matching records found.
The alert right now is located in the submit function in the last bit of code posted
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
})
}
<!doctype html>
<html>
<head>
<title>Salary Info Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="ChicagoEmployees.js"></script>
<script src="demoLS.js"></script>
</head>
<body>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
</body>
</html>
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
if (searchKey.isEmpty()) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
If I understand your question correctly, you can check if there's any matching data at the end of the getlist()
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
// ... codes ...
callBack(results);
// like this
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
// Use with demo.html
// Tested with jQuery 3.1.1, January 2017
// Updated January 2018
// This function is called when the response has returned
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
}
postResult2 = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = namesDepartmentList + list[i].name + "<br/>" + list[i].department + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
}
submit2 = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult2);
console.log("A result should appear now!");
}
$(function() {
$("#start").click(submit);
});
$(function() {
$("#start2").click(submit2);
});
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
if (response.data.length==0) {
alert("No Matching Records Found");
console.log("A result should appear!");
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query for name and Salary" /></p>
<p><input type="button" id="start2" value="Submit Query for Names and Departments" </p>
<h2>First Matching Employing + Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>

Delete duplicate array element

I am working on a program that records customer name and status(child/adult), the program allows add, display and delete customer records from array. However, if user enters the same name and status e.g:
Name: james, status: adult
Name: james, status: adult
I want the function to delete just one record,but now it delete both of them, do i have to add break here? Please help.
PS: I can't use any inbuilt JavaScript functions such as slice(),delete(), concat(), join(), pop(), push(), reverse(), shift(), slice(), sort(), splice(), toString(), unshift() or valueOf()
const MAX_CUSTOMERS = 5;
//create new Array
var customerList = new Array();
function addCustomer() //add customer
{
if (customerList.length >= MAX_CUSTOMERS) //check max customers
alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.')
else
{
var newIndex = customerList.length; //add new user
customerList[newIndex] = new Object;
customerList[newIndex].name = prompt('What is the customer\'s name?'); //ask user enter their name
customerList[newIndex].status = prompt('Are you a Child or an Adult?'); //ask user enter their status
while (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult')) //check user is child or adult
{
customerList[newIndex].status = (prompt('Error! Please Enter \'child\' or \'adult\':'));
}
}
}
function displayAllCustomers() //display customers
{
var message = ''; //create message
for (var i = 0; i < customerList.length; i++) //loop customers
{
message += 'Name:' + customerList[i].name + ', Status: ' + String(customerList[i].status) + '. \n'; //add customer to message
}
if (message == '') //check message
message = 'Sorry, there are no customer to display!';
alert(message); //output message
}
function identifyThenDeleteCustomer() //identify then delete customer
{
var customerName = prompt('Enter the name of the customer to delete:'); //get customer name
var customerStatus = prompt('Enter \'child\' or \'adult\':'); //get customer status
while (!(customerStatus == 'child' || customerStatus == 'adult')) //check customer status
customerStatus = prompt('Error - enter \'child\' or \'adult\':');
deleteCustomer(customerName, customerStatus); //delete customer
}
function deleteCustomer(aName, aStatus) //delete customer
{
var newCustomerList = new Array(); //create new array
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name != aName) || (customer.status != aStatus)) //check customer
{
var newIndex = newCustomerList.length; //add new user
newCustomerList[newIndex] = customer;
}
}
if (newCustomerList.length < customerList.length) //check deleted
{
alert('The customer has been deleted.');
}
else
{
alert('There are no customer to delete!');
}
customerList = newCustomerList; //update customer list
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<title>Coursework 2</title>
<script src="ZouYuncongINSTG018cw2.js" type="text/javascript"></script>
</head>
<body>
<div>
<button type="button" onclick="addCustomer();">Add Customer</button><br>
<button type="button" onclick="displayAllCustomers();">Display All Customers</button><br>
<button type="button" onclick="identifyThenDeleteCustomer();">Identify then Delete Customer</button>
</div>
</body>
</html>
You can make your delete function like this,
function deleteCustomer(aName, aStatus) //delete customer
{
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name == aName) && (customer.status == aStatus)) //check customer
{
customerList = array.splice(i, 1);//delete from array itself
alert('The customer has been deleted.');
return;//stop
}
}
alert('There are no customer to delete!');
}
It will delete just one.
Since you said you cant use built in functions. In that case you have to copy the elements before and after the one to remove. You can have a control variable marking that you already found the one to delete. So no more deletions will happen.
For example,
function deleteCustomer(aName, aStatus) //delete customer
{
var onedeleted = false;
var newCustomerList = new Array(); //create new array
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name != aName) || (customer.status != aStatus) || onedeleted) //check customer
{
var newIndex = newCustomerList.length; //add new user
newCustomerList[newIndex] = customer;
}
else
onedeleted = true;
}
if (newCustomerList.length < customerList.length) //check deleted
{
alert('The customer has been deleted.');
}
else
{
alert('There are no customer to delete!');
}
customerList = newCustomerList; //update customer list
}

Display Contacts in Phonegap

when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}

Categories