I know there are a lot of these questions on Stackoverflow but none of them work for me. I would like to post my own code and try and find out what I am doing wrong.
So, I have a function that adds a bunch of items to an array. The page is never refreshed, as is the way it is designed. So when that same function is called again the array MUST be emptied because:
Items added to an array are linked to a specific item on the page that the user selected.
When a new item is selected the old item's things should not be shown in the array. Only the new item's things.
The array is populated from checkbox values and that array is then used to create different checkboxes on a popup modal form.
Here is the code to populate the array:
// Here I tried emptying the array with below mentioned methods. The array is defined outside of the function. I have also tried defining it inside.
var count = 0;
var optionsSelected = 0;
$('input[name="extrasSelected"]:checked').each(function() {
var selected = $(this).val().split("|");
extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
optionsSelected++;
count++;
});
$('input[name="extrasSelected"]:not(:checked)').each(function() {
var notSelected = $(this).val().split("|");
extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
count++;
});
extras.sort();
This entire thing is working perfectly. Except when I select a new item. The popup displays and checkboxes are created with the previous item's things as well as checkboxes with the new item's things.
I have tried to use:
extras = [];
extras.pop();
extras.length = 0
while (extras > 0) {
extras.pop();
}
Actually, I have tried all methods seen on stackoverflow and google. So I am guessing that I am doing something wrong.
Any help would be greatly appreciated!
EDIT
Additional Code As Requested:
var extras = [];
$("#doLookup").click(function() {
var count = 0;
var optionsSelected = 0;
$('input[name="extrasSelected"]:checked').each(function() {
var selected = $(this).val().split("|");
extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
//alert(extras[0][1]);
optionsSelected++;
count++;
});
$('input[name="extrasSelected"]:not(:checked)').each(function() {
var notSelected = $(this).val().split("|");
extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
//alert(extras[0][1]);
count++;
});
extras.sort();
if (extras.length > 0) {
optionalsJSHead = '<table width="100%"><tr><th style="width: 40%;"><b>Optional Extra</b></th><th style="text-align:right;width:15%"><b>Retail</b></th><th style="text-align:right;width:15%"><b>Trade</b></th><th style="text-align:right;width:15%"><b>Market</b></th><th style="text-align:right"><b>Include</b></th></tr>';
optionalsJSBody = '';
if (parseInt(year) === parseInt(guideYear)) {
for (i = 0; i < extras.length; ++i) {
optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" disabled="disabled"/></td></tr>';
}
} else {
for (i = 0; i < extras.length; ++i) {
if (extras[i][4] == 'notChecked') {
optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'"/></td></tr>';
} else {
optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" checked /></td></tr>';
}
}
}
optionalFooter = '</table>';
optionalsJS = optionalsJSHead + optionalsJSBody + optionalFooter;
}
});
From my understanding, you can create a temporary array, populate it with new values and then assign it to extras variable. See the code below:
var extras = []; // actual array whose items you want to use
$("#doLookup").click(function() {
var tmpExtras = []; // temporary array to get the new items you want.
var count = 0;
var optionsSelected = 0;
$('input[name="extrasSelected"]:checked').each(function() {
var selected = $(this).val().split("|");
tmpExtras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
//alert(extras[0][1]);
optionsSelected++;
count++;
});
$('input[name="extrasSelected"]:not(:checked)').each(function() {
var notSelected = $(this).val().split("|");
tmpExtras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
//alert(extras[0][1]);
count++;
});
tmpExtras.sort();
// now assign tmpExtras to extras array, so that
// you can get the new items
extras = tmpExtras;
// ... rest of code that uses extras
If you should set array as empty before adding some value to the array. I think you should set it in both places before you try to fill it: extras[count] = []; extras[count] = .... . And why do you need the array of array? maybe you should used just array and every time rewrite it? like:
extras = [selected[0], selected[1], selected[2], selected[3], 'checked'];
then no needs to set array like empty before filling.
Your click event is bound to a single item. #doLookup is an id selector which means that there is a single item with the id="doLookup" in the document.
How do you intend to let the function know that the array needs to be emptied?
A simple fix would be to bind the click event to another selector such as .doLookupClass etc and then check inside the function when a different item was selected and empty the array.
It would seem I made a rookie mistake. The array was being emptied. However since I am creating textboxes with javascript I forgot to empty the div before adding the new ones, causing the old ones to still display. And I didn't post that part of the code so that is why you guys probably couldn't assist.
I changed
$("#myDiv").append(OptionalsJS);
to
$("#myDiv").empty().append(OptionalsJS);
What a stupid mistake... X_X anyway, thanks for the assistance anyway!
Maybe the whole thing can be done in a much easier fashion?
See here for a working example
var extras = []; // actual array
$("#doLookup").click(function() {
extras = []; // temporary array
$('input[name="extrasSelected"]').each(function() {
with ($(this)){
var cb=val().split("|");
var state=(is(':checked')?'':'un')+'checked';
}
extras.push([cb[0], cb[1], cb[2], cb[3], state]);
});
$('#show').html(JSON.stringify(extras));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type=checkbox value="a|b|c|d" name="extrasSelected" /><br/>
<input type=checkbox value="e|f|g|h" name="extrasSelected" /><br/>
<input type=checkbox value="i|j|k|l" name="extrasSelected" /><br/>
<input type=checkbox value="m|n|o|p" name="extrasSelected" /><br/>
<input type=checkbox value="q|r|s|t" name="extrasSelected" /><br/>
<input type=checkbox value="u|v|w|x" name="extrasSelected" /><br/>
<input type="button" id="doLookup" value="go"/>
<div id="show" />
Related
I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!
I'm trying to make a small script that allows for a little notes section. This section would have an input box that allows for adding elements to the list; which will be saved in localStorage so they are not lost when I refresh or close the browser. The code I have is as follows (it's all done through JS even the html, but ignore that.)
var notes = [];
var listthings = "<h2 id=\"titlething\">Notes</h2>" +
"<ul id=\"listing\">" +
"</ul>"
"<input type=\"text\" name=\"item\" id=\"textfield\">" +
"<input type=\"submit\" id=\"submitthing\" value=\"Submit\">";
JSON.parse(localStorage.getItem('notes')) || [].forEach( function (note) {
"<li id=\"listitem\">" + notes + "</li>";
})
$('#submitthing').click(function() {
notes.push($('#textfield').val());
});
localStorage.setItem('notes', JSON.stringify(notes));
Also, how would I go about appending the latest added li between the opening and closing tag? Obviously I'd usually do it using jQuery, but this is puzzling me a little. However, only the 'Notes' loads at the top, any ideas?
Your approach is way off the mark. You don't need JSON at all (this just confuses things) and you don't need to manually create HTML.
Also, you can use an array to store the notes, but since localStorage is the storage area, so an array is redundant. Additionally, without using an array, you don't need JSON. The entire problem becomes much easier to solve.
Unfortunately, the following won't run here in this snippet editor, due to security issues, but it would do what you are asking. This fiddle shows it working: https://jsfiddle.net/Lqjwbn1r/14/
// Upon the page being ready:
window.addEventListener("DOMContentLoaded", function(){
// Get a reference to the empty <ul> element on the page
var list = document.getElementById("notes");
// Loop through localStorage
for (var i = 0; i < localStorage.length; i++){
// Make sure that we only read the notes from local storage
if(localStorage.key(i).indexOf("note") !== -1){
// For each item, create a new <li> element
var item = document.createElement("li");
// Populate the <li> with the contents of the current
// localStorage item's value
item.textContent = localStorage.getItem(localStorage.key(i));
// Append the <li> to the page's <ul>
list.appendChild(item);
}
}
// Get references to the button and input
var btn = document.getElementById("btnSave");
var note = document.getElementById("txtNote");
// Store a note count:
var noteCount = 1;
// When the button is clicked...
btn.addEventListener("click", function(){
// Get the value of the input
var noteVal = note.value;
// As long as the value isn't an empty string...
if(noteVal.trim() !== ""){
// Create the note in localStorage using the
// note counter so that each stored item gets
// a unique key
localStorage.setItem("note" + noteCount, noteVal);
// Create a new <li>
var lstItem = document.createElement("li");
// Set the content of the <li>
lstItem.textContent = noteVal;
// Append the <li> to the <ul>
list.appendChild(lstItem);
// Bump up the note counter
noteCount++;
}
});
});
<input type=text id=txtNote><input type=button value=Save id=btnSave>
<ul id=notes></ul>
This is how I would approach it using jquery. but depens how complex this should be. this is just simple demo.
<input type="text" id="note" />
<button id="add">add note</button>
<ul id="notes"></ul>
javascript and jquery
function addNote(){
var data = localStorage.getItem("notes")
var notes = null;
if(data != null)
{
notes = JSON.parse(data);
}
if(notes == null){
notes = [];
}
notes.push($("#note").val());
localStorage.setItem("notes", JSON.stringify(notes));
refreshNotes();
}
function refreshNotes(){
var notesElement =$("#notes");
notesElement.empty();
var notes = JSON.parse(localStorage.getItem("notes"));
for(var i = 0; i< notes.length; i++){
var note = notes[i];
notesElement.append("<li>"+note+"</li>");
}
}
$(function(){
refreshNotes();
$("#add").click(function(){
addNote();
});
})
example:
http://codepen.io/xszaboj/pen/dOXEey?editors=1010
I need to Get data sent from form in popup but the problem that in the form there is many checkboxes with same name like name='list[]' :
JS :
function showPopup(){
var user = document.getElementById("check").value;
var popup = window.open("milestone.php?a="+user,"hhhhhh","width=440,height=300,top=100,left=300,location=1,status=1,scrollbars=1,resizable=1") ;
}
html :
<input type='checkbox' name="approve[]" value="get from Mysql">
<input type='checkbox' name="approve[]" value="get from Mysql">
<input type='checkbox' name="approve[]" value="get from Mysql">
var user = document.getElementById("check").value;
That won't work because:
You need to get multiple values
You need to get the values only of checkboxes that have been checked
You don't have an element with that id (but an id has to be unique anyway)
The fields all have the same name. Use the name.
var inputs = document.getElementsByName("approve[]")
Then you need to generate your form data from it, filtering out the ones which are not checked:
var form_data = [];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.checked) {
form_data.push(encodeURIComponent(input.name) + "=" + encodeURIComponent(input.value));
}
}
Then put all the form data together:
var form_data_query_string = form_data.join("&");
Then put it in your URL:
var url = "milestone.php" + "?" + form_data_query_string;
Then open the new window:
var popup = window.open(url,"hhhhhh","width=440,height=300,top=100,left=300,location=1,status=1,scrollbars=1,resizable=1") ;
If you want to pass the array via get you should loop through all the checked checkboxes and store the value of everyone in array then convert them to Json using JSON.stringify so you can passe them in url :
function showPopup(){
var approve_array=[];
var checked_checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
for(var i=0;i<all_checkboxes.length;i++){
approve_array[i] = checked_checkboxes[i].value;
}
var url = "milestone.php?approve="+JSON.stringify(approve_array);
var popup = window.open(url,"hhhhhh","width=440,height=300,top=100,left=300,location=1,status=1,scrollbars=1,resizable=1") ;
}
In you php page you could get the array passed as Json using json_decode :
$array_of_approves = json_decode($_GET['approve']);
Hope this helps.
You can access the value as:
$approveList= $_POST['approve'];
and can be iterated as
foreach ($approveList as $approve){
echo $approve."<br />";
}
This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)
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;
}
You should use array.splice(position,nbItems)
function removeRecord (i) {
foodList.splice(i, 1); // remove element at position i
var newFood = "";
for (var i = 0; i < foodList.length; i++) {
newFood += "<a href='#' onClick='removeRecord(" + i + ");'>X</a> "
+ foodList[i] + " <br>";
};
document.getElementById('foods').innerHTML = newFood;
}
http://jsfiddle.net/3b4qp/5/
Now using JQuery:
$(function(){
$(document).on('click','input[type=submit]',function(){
$('#foods')
.append('<div>X '
+ $('#addFood').val() + '</div>');
});
$(document).on('click','.item',function(){
$(this).parent().remove();
});
});
http://jsfiddle.net/jfWa3/
Your problem isn't the arrays, your problem is this code:
node.innerHTML += newFood;
This code is very, very, very slow. It will traverse all exising DOM nodes, create strings from them, join those strings into one long string, append a new string, parse the result to a new tree of DOM nodes.
I suggest to use a framework like jQuery which has methods to append HTML fragments to existing DOM nodes:
var parent = $('#foods');
...
for (var i = 0; i < foodList.length; i++) {
parent.append( "<a href='#' onClick='removeReco..." );
That will parse the HTML fragments only once.
If you really must do it manually, then collect all the HTML in a local string variable (as suggested by JohnJohnGa in his answer) and then assign innerHTML once.
Here's some tips to, at least, make your code more portable (dunno if it will be better performance wise, but should be, since DOM Manipulation is less expensive)
Tips
First separate your event handle from the HTML
Pass the "new food" as a function paramater
Tie the array elements to the DOM using the ID
Instead of rerendering everything when something changes (using innerHTML in the list), just change the relevant bit
Benefits:
You actually only loop once (when removing elements from the array).
You don't re-render the list everytime something changes, just the element clicked
Added bonus: It's more portable.
Should be faster
Example code:
FIDDLE
HTML
<div id="eventBinder">
<!-- we add to our foodList from the value of the following input -->
<input id="addFood" type="text" value="food" />
<!-- we call addToFood(); through the following button -->
<button id="addFoodBtn" value="Add more to food">Add Food</button>
<!-- The list of food is displayed in the following div
-->
<div id="foods"></div>
</div>
JS
// FoodList Class
var FoodList = function (selectorID) {
return {
foodArray: [],
listEl: document.getElementById(selectorID),
idCnt: 0,
add: function (newFood) {
var id = 'myfood-' + this.idCnt;
this.foodArray.push({
id: id,
food: newFood
});
var foodDom = document.createElement('div'),
foodText = document.createTextNode(newFood);
foodDom.setAttribute('id', id);
foodDom.setAttribute('class', 'aFood');
foodDom.appendChild(foodText);
this.listEl.appendChild(foodDom);
++this.idCnt;
},
remove: function (foodID) {
for (var f in this.foodArray) {
if (this.foodArray[f].id === foodID) {
delete this.foodArray[f];
var delFood = document.getElementById(foodID);
this.listEl.removeChild(delFood);
}
}
}
};
};
//Actual app
window.myFoodList = new FoodList('foods');
document.getElementById('eventBinder').addEventListener('click', function (e) {
if (e.target.id === 'addFoodBtn') {
var food = document.getElementById('addFood').value;
window.myFoodList.add(food);
} else if (e.target.className === 'aFood') {
window.myFoodList.remove(e.target.id);
}
}, false);
Here is another sugestion:
function remove(arr, index) {
if (index >= arr.lenght) { return undefined; }
if (index == 0) {
arr.shift();
return arr;
}
if (index == arr.length - 1) {
arr.pop();
return arr;
}
var newarray = arr.splice(0, index);
return newarray.concat(arr.splice(1,arr.length))
}