Turn off dynamically created buttons using jQuery

Whenever a user selects a checkbox in a table row and saves it, a new container is created to store the data in a specific format for that particular row.

Note: The data displayed in the table is sourced from JSON.

Additionally, users have the option to manually add data to the same container using a form.

Later on, all these containers or data holders will be appended to a parent container in the DOM.

Although I have successfully managed to swap these data containers, I am facing an issue with disabling or hiding buttons for the first and last containers.

Below is the script I am using:

<script>
    // Code goes here
</script>

The top button for the first data holder should be disabled as there is no container above it to swap. Similarly, the down button for the last data holder should be disabled as there is no container below it to swap with.

I'm unsure about what might be wrong with my implementation?

Note: Everything works perfectly when using hardcoded data holders instead of generating them dynamically.

Answer №1

To properly handle event delegation, make sure to include a delegated listener.

$('ParentElementWithStaticReference').on('event', 'TargetElementToObserve', function() {
  // Implement desired functionality here
});

Answer №2

When dealing with elements that are generated dynamically, it is recommended to utilize delegated event handlers in the following manner:

$("body").on("click", selector, function() {
     //perform desired actions
});

Answer №3

Below is the full code snippet.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
        <style>
            .parent {
                height: 25%;
                width: 90%;
                padding: 1%;
                margin-left: 1%;
                margin-top: 1%;
                border: 1px solid black;

            }

            .parent:nth-child(odd){
                background: skyblue;
            }

            .parent:nth-child(even){
                background: green;
            }

            .disabled-btn {
              cursor: not-allowed;
              opacity: 0.25%;
            }

        </style>
    </head>
    <body>
        <button class="btn btn-primary" onclick="getData()">Get Data</button>
        <form>
            <label>Count: </label>
            <input type="text" placeholder="Enter a count" id="mycount">
            <button onclick="saveData()">Submit</button>
        </form>
        <div class="box">

        </div>



    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        var content = "";

        function getData(){

                for(var count=0; count<4; count++){

                content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

                }
                $('.box').html(content);

            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });


            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();


                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }


            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertAfter($(toMove1).next());

                    handleEvents();
                });

                $('.top-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertBefore($(toMove1).prev());
                    handleEvents();
                });

            }


    </script>
    </body>
</html>


            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn"><Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();


                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }


            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var   
   assist

                };

            

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

Troubleshooting: iOS Web App Splash Screen fails to load

I'm having trouble displaying a splash screen on my web app for iOS devices. Upon launching the app from the home screen, I only see a white screen with no content loading. Interestingly, if I rearrange the meta tags to be below the icons and splash s ...

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Preserving proportions in CSS using both width and height measurements

My objective is to set an aspect ratio (for example, 4:3) for a DIV and all its children with the styles WIDTH:100% and HEIGHT:100%. Initially, this method works well by setting the parent's WIDTH:100% and then adding PADDING-BOTTOM: 75%; // (3/4)*1 ...

Displaying identical information in a bootstrap dropdown menu

I am working on implementing a navigation bar with Bootstrap dropdown functionality. Each button in the navbar has the same content displayed in the dropdown menu, such as the "Exercises" button showing assignments and the "Assignments" button also displ ...

Dynamic HTML element

I created an input number field and I want to dynamically display the value of this field in a container without having to refresh the page. I am currently using ajax for this purpose, but unfortunately, I still need to reload the page. HTML: < ...

Conflict between Play framework and jQuery AJAX calls

Hi there, I have a simple issue, Currently, my application is utilizing Play framework 2.1, and at times I need to send multiple independent ajax requests using jQuery. For example: $.get('/url1', function(res){ ... }); $.get('/url2' ...

Obtaining a specific data point from a JSON object sourced from Twitter

I've tried numerous methods, but I'm struggling to access the data I need in JavaScript. Every time I attempt it, I either get an 'undefined' error or can't access the property of 'x'. Here's the object I'm wor ...

Utilizing a flexbox container within a table container, implementing PRE tags for handling overflow

Currently, I am diligently working on an intricate DASHBOARD utilizing bootstrap-4. A peculiar issue arose with the implementation of <pre> within a Flexbox. However, upon closer inspection, it became evident that this was not a flexbox or <pre> ...

Is there a way I could customize this design to include buttons that smoothly navigate to the following section?

I'm attempting to create a Web Page that scrolls horizontally. Currently, the template relies on J Query and CSS to manage width but users must still manually drag the scroll bar at the bottom of the page. Is there a way to incorporate arrows or click ...

Enable jquery offsetParent() function

$(document).ready(function(){ $("button").click(function(){ if ($("p").offsetParent().css("background-color") === "red") { $("p").offsetParent().css("background-color", "yellow"); } else { $("p").offsetParent().c ...

Create an HTML div element that spans the full width of the

I'm facing an issue on my HTML page where a div containing users from a chat system database is not displaying correctly. The ul li tag within the parent div is not taking up the full width as expected. Here's how it should look: http://prntscr.c ...

Unable to render nested HTML tag in simple React.JS component

I'm currently working on setting up my first component. After following a tutorial, I tried implementing their code to create the component. The code does inject the first <div> into the HTML document, but the <h1> element is missing. In ...

Tips for transferring a value from a Swift UITextField to a text field within an HTML form in a WKWebView using Swift

Consider the following HTML form: <p> <form> <input type="text" id="result" name="Result" width="20"/> </form> </p> I'm currently working on passing a String value from my UITextField in Swift to this ...

JavaScript: Hover Effects and Toggle Functions

My navigation menu is set to hide by default and should only appear when hovered over, however it seems to disappear immediately after showing up. I want the navigation menu to stay visible on hover and then hide again when the mouse moves out of the ele ...

Setting up Jquery autocomplete with jquery 1.6.2: A step-by-step guide

I have encountered an issue with jQuery autocomplete when using the latest version, 1.6.2. It was working perfectly fine with version 1.2.6, but now it is not functioning as expected with the latest update. I have attempted to bind my textbox within the do ...

Please click the provided link to display the data in the div. Unfortunately, the link disappearance feature is currently not

What I'm Looking For I want the data to be displayed when a user clicks on a link. The link should disappear after it's clicked. Code Attempt <a href="javascript:void(0);" class="viewdetail more" style="color:#8989D3!important;">vi ...

problem with overlapping elements

Hey there! I'm facing a CSS issue where an error message appears below the contact us box if the user doesn't fill the text box properly. However, there's an overlap issue with the image below the contact us box. Any suggestions on how to s ...

The website takes forever to load on Internet Explorer and it keeps freezing

When attempting to access a certain website, there is a noticeable delay before the page actually loads (especially when using older versions of Internet Explorer). The issue does not occur with other web browsers. The website in question is a simple Word ...

What new features have they incorporated into the latest Foxy Bingo website?

Foxy Bingo has recently unveiled a new website at www.foxybingo.com that operates as a single-page site, allowing users to click on main menu items to navigate through the content by scrolling down the page. Interestingly, when a link is clicked, the URL ...