javascript guide on eliminating a particular element from an array by detecting the clicked item

I am looking to enhance my list by enabling the functionality to remove items permanently from the array when they are clicked. Although I have successfully implemented the removal feature using remove(), the issue arises when a new item is added to the array as it reappears along with the newly added item.

To view the code in action, please visit my JSFIDDLE account: http://jsfiddle.net/trav5567/3s64o1ta/1/

Javascript

      function testArray(){
       var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];
       function initArray(){
        loopArray();
       }initArray();
       function myFruit(){
         $('#addFruit').on('click', function(e) {
          e.preventDefault();
          var flag = true;
          var val = $('#fruitAdd').val();
          for(var i = 0 ; i < Fruit.length ; i ++){
            if(Fruit[i] == val){
              flag = false;
              console.log('already entered this item');
             }        
           }
           if(flag){
            Fruit.push(val);
            loopArray();
           }
         });
         }myFruit();
         function loopArray(){
           var fruitList = $('ul.fruit');
           var arrayContainer = $('.arrayContainer');
           fruitList.empty();
           for(var i = 0; i< Fruit.length; i++){
             fruitList.append('<li>'+Fruit[i]+'</li>');
           }
          }
         function removeItem(){
            var itemClicked = $('ul.fruit li');
            itemClicked.on('click', function(){
               $(this).remove();
            });
         }removeItem();
       }testArray();

Answer №1

To properly remove an item from an array when clicked, you need to not only remove the li tag containing the element but also use the splice method to remove the element from the array:

var itemClicked = $('ul.fruit li');
itemClicked.on('click', function () {
    $(this).remove();
    var item = $(this).text();
    var index = Fruit.indexOf(item);
    Fruit.splice(index, 1);
});

View the Working Fiddle Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring React components - comparing mount and shallow rendering techniques and practicing event simulation

Recently, I've been delving into testing React components and have encountered a challenge. Specifically, I am striving to simulate entry into the input field identified as 'componentCount' in my code. My experience with React spans less tha ...

What is preventing me from accessing a function that is declared using function declaration while using a debugger?

When pausing at the debugger statement, an attempt to call foo results in a ReferenceError. It appears that the function is not defined within the script's context or scope, similar to how a local variable like x is. The script example.js is as follo ...

I'm experiencing a strange issue where the timezone offset is being doubled on my computer, yet it is functioning correctly on the UTC

A situation has arisen where the timezone offset on my local server is being duplicated by the server while creating a new event in my app. For every event created by a user, the client-side scripting computes and adds the time zone offset to the input be ...

The validity of AngularJS form is constant and always returns true with formName.$valid

I am facing an issue with my Angular application form where even though the input fields are blank, formName.$valid is always true. Below is the HTML code for my form: <form name="contactForm" novalidate ng-submit="processForm(formData)" autocomplete=" ...

An issue arises when trying to loop using a while loop within an HTML structure

I have a small project with a predefined format, where I need to select a value from a dropdown menu and use that value to fetch data from a database and display it in HTML. While I am able to retrieve the data from the database based on the selected value ...

Expanding and collapsing DIV elements using JavaScript upon clicking navigation menu items

At present, the current code unfolds the DIVs whenever a user clicks on a menu item. This results in the DIV folding and unfolding the same number of times if clicked repeatedly on the same link, without staying closed. My desired functionality is to have ...

What is the best way to merge arrays of aliases in Perl?

Is there a more efficient way to concatenate arrays of aliases in Perl while maintaining aliases in the resulting array? One possible solution is: my ($x, $y, $z) = 1 .. 3; my $a1 = sub {\@_}->($x); my $a2 = sub {\@_}->($y, $z); my $a3 ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

You can obtain the values of multiple div selections using jQuery

In a display with two columns, I want to be able to perform a common operation (such as delete) based on the selection of certain div IDs. If a user selects the div IDs participant_1, participant_4, participant_6 at the same time, I need to collect these ...

CordovaJS encountered an error due to a failed manifest merger: the minimum SDK version cannot be lower than version 19 as declared in the code

For the past 48 hours, I have been struggling to build my Cordova app for Android. Every time I attempt to open my project in Android Studio, I encounter an error during the gradle sync process in the run tasks phase: ERROR: Manifest merger failed : uses- ...

Organizing Vue.js components into separate files for a cleaner view model architecture

Having smooth functionality in a single file, I encountered difficulties when attempting to break up the code into multiple files and bundle it in a .vue file. Below is the final .vue file for simplicity. Here is the HTML file: <!DOCTYPE html> < ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

When attempting to execute Protractor tests, an error occurs stating that the object #<Object> does not possess the 'getInstance' method

Whenever I try to run my Protractor tests from the command line, all of them fail because the protractor object does not have the necessary methods. The error message I receive is: TypeError: Object # has no method 'getInstance' Although this ...

Getting the ThreeJs OrbitControl import version directly from the CDN

Using threejs from CDN and requiring OrbitControl as well, I encountered an issue with importing both Three and OrbitControl using the latest version 0.148.0: import * as THREE from 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__ ...

The method element.isDisplayed() is indicating a false value even though the element is visibly present on the screen

element.isDisplayed() is returning false even though the element is visible on the screen, causing issues with clicking on it. I attempted to use the code below, but without success. Actions cursor = new Actions(driver); cursor.moveTo ...

The process of accessing XMLHttpRequest in Angular

How can I enable XMLHttpRequest in Angular? I am trying to access getData.php and encountering the following error: Access to XMLHttpRequest at 'http://localhost:8888/*****/****/getData.php' from origin 'http://localhost:4200' has been ...

Framer motion layout animation fails to account for page scrolling during transitions in NextJs routes

Currently, I am working on a fascinating NextJS project that showcases a series of interactive blocks. As the user navigates through the app, these blocks dynamically adjust their size and position on the screen. To achieve this effect, I'm leveragin ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...