Tips for using jQuery to create a delete functionality with a select element

I'm relatively new to utilizing jquery. I decided to tackle this project for enjoyment: http://jsbin.com/pevateli/2/

My goal is to allow users to input items, add them to a list, and then have the option to select and delete them by clicking on the top right image.

JavaScript:

$(document).ready(function(){
    $("#button").click(function(){
        $(".del").slideDown(100);
        var toAdd = $('input[name=checkListItem]').val();
        $(".list").append("<div class='item'><input type='checkbox'/>" + toAdd + "</div>");
    });
});
$(document).on("click",".del",function(){
var rmv = $("input:checkbox:checked").val();
    $(rmv).remove();
});

HTML:

<!DOCTYPE html>
<html>
<head>
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <title>To Do</title>
    <link rel="stylesheet" type="text/css" href="a style.css"/>
    <script type="text/javascript" src="a script.js"></script>

</head>
<body>
    <h2>To Do</h2>
    <form name="checkListForm">
        <input type="text" name="checkListItem"/>
    </form>
    <img style="display:none;" class='del' src='del.png' align='right' width='20px'>    </img>
    <div id="button">Add!</div>
    <br/>
    <div class="list"></div>
</body>
</html>

CSS:

h2 {
    font-family:arial;
}

form {
    display: inline-block;
}

#button{
    display: inline-block;
    height:20px;
    width:70px;
    background-color:#cc0000;
    font-family:arial;
    font-weight:bold;
    color:#ffffff;
    border-radius: 5px;
    text-align:center;
    margin-top:2px;
}

.list {
    font-family:garamond;
    color:#cc0000;
}

If you'd like to see it in action, here's the live link: http://jsbin.com/pevateli/2/

Answer №1

http://jsbin.com/pevateli/3/

Your delete code had some errors as pointed out by Ramy. It was also suggested to select the parent item, which has been implemented in this updated code.

Furthermore, I have changed the event from

$(document).on('#button', 'click', function() {});
to a submit function using
$(document).on('form', 'submit', function() {});
. The div has also been changed to a button type submit so you can either hit enter or click the button to add an item.

Additionally, I have added functionality to remove the input's value on submit, making it easier to create new items without manually deleting the previous one first.

Lastly, wouldn't it be really fun to incorporate localStorage(); into this code?

Answer №2

If you want to remove the checked checkboxes along with their containers, you can achieve this by running through the checkboxes and checking if they are checked before deleting the container:

$(document).on("click",".del",function(){
    $('.checkbox:checked').parents('.item').remove();
});

I have included the class checkbox for the checkboxes so that it can be used as a selector instead of directly targeting the input element. It's always advisable to keep your JavaScript logic independent of specific DOM elements.

You can view a live demo of this solution here

Answer №3

var selectedCheckbox = $("input:checkbox:checked").val()
grabs the input value, which may not be what you need.

The solution you are seeking is as follows:

$(document).on("click", ".delete", function () {
    // For more precision, consider using $('.item input:checked') or even $('.list input:checked') or assign a class to the checkboxes.
    $('input:checkbox:checked').closest('.item').remove();
});

An example can be found here: http://jsfiddle.net/scottux/72ZxC/

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

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...

What is the best method for retrieving data through an ajax call in my modular JavaScript setup?

Working with a basic modular JavaScript structure, my goal is to request a random quote from an API and display it on an HTML page using Mustache.js. I previously achieved this without the modular approach, but now I'm attempting it in a more structur ...

Tips on saving php variable content in HTML "id"

Three variables are used in PHP: message_id, message_title, and message_content. Their content is stored inside HTML 'id' for later use with jQuery. Example: Variables: $id_variable = $rows['id_mensagem']; $message_title_edit = $rows ...

Encountering the 404 Not Found error when trying to fetch the Next.js API Route from the app

Currently facing difficulties with the routing in Next.js 13's app. Every time I attempt to access it, for instance via Postman, I keep getting a 404 Not Found error. This is my file structure: https://i.stack.imgur.com/ZWrlb.png An example of one ...

Tips for successfully passing an array containing multiple values within the jsPDF body

I'm experimenting with jsPDF to showcase a list of products that users have ordered. I've managed to set up my columns and generate the PDF for download, but I'm facing some challenges with populating the body section. When attempting to sen ...

How does a JS event impact the state transition in a backend state machine built on Rails?

I am currently developing a new project where the backend involves Users who have multiple "Courses" each containing multiple "Steps". My goal is to create a JavaScript function that validates the user's answer. For example, if the user inputs "6", w ...

A guide on merging existing data with fresh data in React and showcasing it simultaneously

As a newcomer to Reactjs, I am facing the following issue: I am trying to fetch and display new data as I scroll down Every time I scroll down, I fetch the data and save it in Redux. However, due to pagination, only 10 items are shown and not added to th ...

Transferring HTML5 Video data by breaking it into segments and streaming it through several HTTP/

Looking for ways to speed up the loading time of an html5 video? Is there a method to make a browser process each webm video fragment as individual TCP streams, in order to take advantage of HTTP/2's enhanced parallelization? ...

Creating customized JQuery UI tabs to perfectly accommodate the available horizontal space

Can JQuery UI Tabs be modified to fill the horizontal space and stack to the left? In order to achieve this, could we consider using a markup like the one below: <table width="100%"> <tr> <td> ...content... </td> ...

How to eliminate properties from a nested array using D3

I've been attempting to filter out specific attributes from an array using D3. The array consists of values from a CSV file. Everything went smoothly for a small CSV file when I did it like this: d3.csv("foods.csv", function(data) { data.forEach(fun ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Tips for submitting JSON data to the specified input area with AngularJS

I have a json object that looks like this: var jsondata = { "id": 1, "name": "Test Name", "price": 100, "city": "XYZ" }; I am trying to post/send this data to a specific url location when the Send button is clicked. The url location can be entered in an ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

The MediaSource API is not supported on Chrome 27

My current browser version is Chrome 27, and based on this source, it is indicated that the MediaSource API comes pre-installed. However, upon further examination on the same page, the test section states that Your browser does not support the MediaSource ...

Solution to bypass JavaScript PHP login system

Creating a login/register system with JavaScript to display specific divs for the system: 1st div = menu option to either log in or register 2nd div = shows login form or register form depending on what was clicked (login or register) 3rd div = displays ...

Create a new template following rendering in VueJS

I am facing an issue while using the datatable jQuery plugin with vueJs. Whenever I try to use the render function of the datatable and include vueJs code like @click, it doesn't get interpreted. Instead, in the source code, @click is visible but noth ...

Remember a MySQL query using JavaScript

For quite some time, I've been on a quest to unveil the solution to this issue that seems relatively straightforward, yet continues to elude me. The crux of the matter is my desire to "recall" a functional mysql query. With an HTML button and a span ...

Obtaining values from event listeners in Vue.js across different methods

Looking for guidance on the code snippet provided below. Is there a way to assign the value of "e.detail.name" to "nodeName," and then access it in a different method within the component for an API request? data() { return { nodeName: '' ...

The Impact of Spaces in Inline Scripting within Asp.NET

As I was coding in JavaScript on an Asp.NET page today, I encountered a small issue. Here's what happened: <script type="type/javascript"> var elementID = document.getElementById("<%=txtMyServerControl.ClientID %>") </script> T ...

Nodejs and express authentication feature enables users to securely access their accounts by verifying their identity before they

I am currently working on a straightforward registration page that needs to save user input (name, email, password) into a database. My tools for this task are express and node. What I am experimenting with is consolidating all the database operations (suc ...