Is it possible to have more than one button for each item on my Shopping List App?

I am developing a shopping list app that allows users to add items to a list. Each item added triggers the display of a button next to it, enabling users to remove the item from the list when needed.

However, a problem arises as more items are added – instead of having one button per item, multiple buttons start appearing for each item in the list. This is not the intended behavior; there should only be one button per item. Can you review my code and provide some assistance? Thank you!

$(document).ready(function() {

  $('#removebox').hide();

  //When you click send it sends the item to the list
  $('#send').click(function() {
    var userMessage = $('.text-box').val();
    $('.text-box').val('');

    //If theres nothing in the text-box and send is clicked an alert pops up
    if (!userMessage) {
      alert("Please add some items to the list!")
    } else {
      //This appends the item typed into the text-box to the list
      $('.container').append('<li>' + userMessage + '</li>');
      addBox();
    }
  });


  //This adds the remove button next to each item in the list      
  function addBox() {
    $('.container li').append($('#removebox'));
    $('#removebox').show();

  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title" width="100%">
  <p> Shopping List</p>
</div>

<div class="container">
  <input class="text-box" placeholder="Please enter an item">
  <button id="send">submit</button>
  <button id="removebox">X</button>
</div>

Answer №1

Why do you duplicate the button every time? Since he has an id, copying him is not allowed anyway.

The actual issue, as pointed out by @tyler mackenzie, is that your '.container li' selector will target all items, not just the last one.

Here's some code to address those problems:

$(document).ready(function() {
  //When you click send it sends the item to the list
  $('#send').click(function() {
    var userMessage = $('.text-box').val();
    $('.text-box').val('');

    //If there's nothing in the text-box and send is clicked, an alert pops up
    if (!userMessage) {
      alert("Please add some items to the list!")
    } else {
      //This appends the item typed into the text-box to the list
      var remBtn = $('<button class="removebox">');  // this creates a new button element
      remBtn.text('X');
      var li = $('<li>');
      li.text(userMessage);
      li.append(remBtn);
      $('.container').append(li);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title" width="100%">
  <p> Shopping List</p>
</div>

<div class="container">
  <input class="text-box" placeholder="Please enter an item">
  <button id="send">submit</button>
</div>

Answer №2

https://jsfiddle.net/62afjy7r/

Essentially, I made changes to how the button is hidden/shown by using CSS for hiding, and also cloned it during the appending process to each element. Additionally, I restructured the HTML slightly by placing the initial content within its own div.

<div class="container">
  <div class="input-container">
    <input class="text-box" placeholder="Please enter an item">
    <button id="send">submit</button>
    <button id="removebox">X</button>
  </div>

</div>

--- css ---
.input-container #removebox {
  display: none
}

--- js ---
function addBox(){
    $('.container li:last-child').append($('#removebox').clone());
     //$('#removebox').show();

};

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

Access files directly through our convenient file storage site

I'm currently delving into the world of angular JS, and I've come across $https. I was looking to upload a file called db.php which includes: { "vcRecords": [ {"name":"Madison" ,"nickName":"Madilove" ,"coderType":"Injection / Fortre ...

What is the best way to split two sets of radio buttons with the same name into distinct blocks in an HTML form?

For my project, I am working with two sets of radio buttons where the values are stored in a Database. Depending on another result in the HTML form, I need to display one set of radio buttons or the other. The issue arises when using the same name for all ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

stop an html page from opening a new window

When using my HTML-based application, there are instances when it needs to open another URL within an iframe. However, a problem arises when the third-party URL within the iframe also opens a new window with the same content and URL. How can I prevent th ...

Import ES6 code by wrapping it in parentheses

Currently delving into React Native and I'm intrigued by the parentheses used in the first line of import. import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Co ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

In the world of MUI, how should one interpret the symbols '&', '>', and '*' when used together?

Currently, I am in the process of building a website using React. To help with this project, I purchased a Material-UI React template. As I was going through the code, I came across the line 4 where it mentions '& > *', and I'm not qu ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Feeling puzzled by the code snippet for vuejs-templates using webpack-simple?

Just starting out with javascript. Learning Vue.js through example reading. But feeling confused by the code snippet from vuejs-templates/webpack-simple. Specifically line 25 data () { return { msg: 'Welcome to Your Vue.js App' ...

The JSON response is displaying [object object] instead of an array

I am currently facing an issue with my Sencha touch app where the json data I am feeding into it is not returning the image URLs as expected. Instead, it is showing me "[object Object]" when I console.log the "images" property. Here is a snippet of the js ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Updating data in React Native fails to activate useEffect, leading to the screen not being refreshed

I'm facing a challenge while working on a recipes app using Firebase Realtime database. I have a functional prototype, but I am encountering an issue where the useEffect hook does not trigger a reload after editing the array [presentIngredients]. Her ...

Is it possible to modify the cell color or highlight in Excel through Node.js?

Hi there, I'm curious if it's possible to highlight a cell in an .csv file using Node.js. I've been able to successfully write to the file, but now I want to emphasize the headings. ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...

Is there a way to compare two regex values using vuelidate?

Can someone assist me with validating an input field using vuelidate? I am looking to return a valid result if either of the two regular expressions provided below is true. const val1 = helpers.regex('val1', /^\D*7(\D*\d){12}\ ...

Nginx try_files not functioning properly for serving css and images

I am attempting to route any requests that come from https://example.com/user/whatever to my "Get Our App" page located at https://example.com/get_app.html Within my nginx.conf file, I have configured the following block: #Redirecting all requests under ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...