Utilizing jQuery to delete items once their corresponding checkboxes are checked

I have successfully implemented a feature where I can add more fields by clicking a button. However, I am facing an issue when trying to delete a field after checking the checkbox. Any assistance on this matter would be greatly appreciated.

jQuery:

$(document).ready(function () 
{
    var x = 0;
    $('#addmore').click(function (e) 
    {
        e.preventDefault();
        if(x<5)
        {
            $("#Files").append("<div id='dummy'></div><input name='file' id='file" + x + "' type='file'/>");
            $("#Files").append("<input value='remove' id='but" + x + "' data-id='" + x + "' type='checkbox'/>");
        }
        else
        {
            alert("max 5 images to be uploaded");
        }
        x++;
    });

    $("#imageForm").on('click', 'input[value="Delete"]' , function () 
    {
        var id = $(this).data('id');
        if($(this).is('checked'))
        {
            $("#file" + id).add(this).add("#dummy").remove();
        }
    });
});

HTML:

<form name="imageForm" id="imageForm" method="post" enctype="multipart/form-data" action="imageuploadlogic.jsp">
    <input type="button" id="addmore" value="addmore"/><input type="button" id="Delete" value="Delete"/>
    <div style="clear: both;"></div>
    <div id="Files"></div>
    <div style="clear: both;"></div>
    <input type="submit" id="submitimage" />
</form>

Answer №1

To improve the structure of the new element set, opt for wrapping all file and checkbox elements inside a div instead of using a dummy div as demonstrated below.

$('#addmore').click(function (e) {
    e.preventDefault();
    var len = $("#Files > .ct").length;
    if (len < 5) {
        $("#Files").append("<div class='ct'><input name='file' type='file'/><input  value='remove' type='checkbox'/></div>");
    } else {
        alert("max 5 images to be uploaded");
    }
});
$("#imageForm").on('click', 'input[value="Delete"]', function () {
    $('#Files div.ct').has('input:checkbox:checked').remove()
});

Utilize the .has() method to locate the ct elements containing checked checkboxes and eliminate them accordingly

Interactive Example: Fiddle

Answer №2

Check out my solution:

JSFiddle

$(document).ready(function () {
        var x = 0;
        $('#addmore').click(function (e) {
            e.preventDefault();
            if(x<5){
            $("#Files").append("<div id='dummy'></div><input name='file' id='file" + x + "' type='file'/>");
            $("#Files").append("<input  value='remove' id='but" + x + "' data-id='" + x + "' type='checkbox'/>");
            }
            else{
                alert("max 5 images to be uploaded");
            }
            x++;
        });
        $("#imageForm").on('click', 'input[value="Delete"]' , function () {
            var id = $(this).data('id');
            $('input[type="checkbox"]:checked').each(function(){
           $(this).add($(this).prev()).remove();
            });
        });

    });

If this helps, consider marking it as the correct answer!

Answer №3

Here is a solution to your issue using a different approach. You will need to follow the same process to remove the elements.

See it in action: Demo

HTML Markup:

<input name="" type="checkbox" value="" id="imageForm">
    <div id="file">This is a paragraph</div>

JavaScript:

$("#imageForm").change(function() {
            if( $(this).prop('checked') ){
                $("#file").remove();
            }
        });

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

When the page is refreshed, the JavaScript may not function properly

Utilizing the jqm Ajax method to retrieve data from servers is causing an issue when transitioning from page1 to page2 and clicking refresh. The data is not being updated, requiring the browser to be exited and reopened to see the changes. Can anyone offer ...

Ensured static element-UI table dimensions even with modifications to columns

Creating an Element-UI table and using v-if to control column show/hide has been working perfectly, except for one small issue. The table seems to automatically change size when columns are shown/hidden, even though I have already set fixed width and heig ...

Issue with utilizing Vuejs variable in Google Maps Matrix API function

Having trouble accessing a Vue.js variable in a function using the Google Maps Matrix API. I am trying to use the Google Distance Matrix API to calculate the distance between two locations. I have declared a variable globally and changed it within a functi ...

What is the best way to erase the contents of a pop-up window?

Whenever I click on an event in the calendar, a popup window appears displaying textboxes and a list of items. The issue arises when I close the popup after selecting an event with items in the list; the same items show up for other events without refreshi ...

What is preventing my HTML from rendering on the page?

I have cross-referenced the script below with the google charts documentation available at the following link: https://developers.google.com/chart/interactive/docs/gallery/scatterchart However, it is not displaying properly. I have reviewed the code and ...

What is the best way to allow only 3 active button checkboxes simultaneously?

HELP NEEDED: How can I limit the ACTIVE state on Jquery to only 3 Active Buttons? I am struggling to create a straightforward button checkbox group where users are allowed to select a maximum of 3 active checkboxes at a time. https://i.sstatic.net/E3EWG. ...

Enhancing HTML element appearance in TypeScript and Angular: A guide to adding style

I have been attempting to apply the flex-grow property to an element, but it does not seem to be taking effect. Here is the script I am using: (this.elementRef.nativeElement as HTMLElement).setAttribute( 'style', 'flex-grow:&apo ...

Setting focus on the require attribute for the <input> tag in a React application

I have a login/register form with multiple input tags. My goal is to automatically set focus and require attribute on the first input tag when the form is opened. I have tried using jQuery and JavaScript to add the required attribute, which works fine. H ...

JavaScript Regular Expressions: Naming Conventions

While many of us are familiar with naming conventions in R, regular expressions remain uncharted territory for me and the most dreaded aspect of my programming endeavors. As I dive back into JavaScript, I am grappling with creating precise RegExp to valida ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Troubleshooting: Unable to preview Facebook Page plugin

When I visit the Facebook developer site to get the code for a Facebook page plugin, I use this link. The preview feature works perfectly with pages like "facebook.com/Nike", but when I try it with my own page, "facebook.com/BargainHideout", it doesn&apos ...

Angular applications can redirect to their own internal pages when linking to an external URL

I've recently started using Angular and have encountered a minor issue. My routing setup is working as expected in the navbar, but I have a link that points to an external URL. When I click on it, instead of redirecting me to the external site, it ta ...

In Typescript, object properties make assertions about other properties within the object

I have a specific object that I use to store data received from an API. This object is structured as follows: class Storage { isReady: boolean = false; content: object || null = null; } I have noticed that when isReady is false, content is null. Con ...

Tips for turning off server-side sorting in Datatables

Following up on my previous question here, I am utilizing Datatables with server-side processing. $('#dataTables1').DataTable({ "bProcessing": true, "bPaginate": false, "serverSide": true, "ajax":{ ...

What steps can be taken to troubleshoot the 'unimplemented or irrational conversion requested' error?

I am facing an issue with passing a substantial amount of records as a stringify object from the client to the server. On the server side, there is a function named 'Get_Records' that is supposed to receive and process this string object by parsi ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

(discovered: [object Promise]) utilizing Material UI and DexieJS

Exploring DexieJS and Material UI for the first time has been quite a learning experience, so I may have overlooked a crucial aspect. Here is a glimpse of my code: Subscreen.tsx const [fightersArray, setFightersArray] = useState<FighterEntity[]>([]) ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

Mastering the art of using div boxes in boxing form

When I box in information using divs, I've noticed that sometimes the wrapping boxes don't fill out the space completely. This can result in elements from other wrappers encroaching into the box area. For example: <div> <div style="le ...