10
rated 0 times
[
17]
[
7]
/ answers: 1 / hits: 28819
/ 12 Years ago, mon, february 11, 2013, 12:00:00
folks! Today I created this script that has the following functionality:
- add new items to array
- list all items from the array
- remove an item from the array
There are two functions:
- addToFood() - adds the value of input to the array and updates
innerHTML of div - removeRecord(i) - remove a record from the array and updates
innerHTML of div
The code includes 3 for loops and you can see it at - http://jsfiddle.net/menian/3b4qp/1/
My Master told me that those 3 for loops make the solution way to heavy. Is there a better way to do the same thing? Is it better to decrease the loops and try to use splice? Thanks in advance.
HTML
<!-- we add to our foodList from the value of the following input -->
<input type=text value=food id=addFood />
<!-- we call addToFood(); through the following button -->
<input type=submit value=Add more to food onClick=addToFood();>
<!-- The list of food is displayed in the following div -->
<div id=foods></div>
JavaScript
var foodList = [];
function addToFood () {
var addFood = document.getElementById('addFood').value;
foodList.push(addFood);
for (i = 0; i < foodList.length; i++) {
var newFood = <a href='#' onClick='removeRecord( + i + );'>X</a> + foodList[i] + <br>;
};
document.getElementById('foods').innerHTML += newFood;
}
function removeRecord (i) {
// define variable j with equal to the number we got from removeRecord
var j = i;
// define and create a new temporary array
var tempList = [];
// empty newFood
// at the end of the function we refill it with the new content
var newFood = ;
for (var i = 0; i < foodList.length; i++) {
if(i != j) {
// we add all records except the one == to j to the new array
// the record eual to j is the one we've clicked on X to remove
tempList.push(foodList[i]);
}
};
// make redefine foodList by making it equal to the tempList array
// it should be smaller with one record
foodList = tempList;
// re-display the records from foodList the same way we did it in addToFood()
for (var i = 0; i < foodList.length; i++) {
newFood += <a href='#' onClick='removeRecord( + i + );'>X</a> + foodList[i] + <br>;
};
document.getElementById('foods').innerHTML = newFood;
}
More From » arrays