0

I have a script that will append to two places on my web application. One is a list item and the other is a hidden field on a HTML form (which I process the data in a PHP service file).

However, I want that if a user clicks the 'x' icon that all the elements are removed that have the same ID.

I have a good idea how to do this but my script below doesn't even log the ID. The .control block is giving me the issue. The #add code block successfully appends the HTML.

Am I missing something obvious?

$("#add").click(function() {

    // RENDER LIST
    var playerList = ""; //
    playerList += "<li class='selection'>" + $("#player").val() + "<i class='fa fa-close control' data-id='" + $("#playerGUID").val() + "'> </i>" + "</li>";

    $(playerList).appendTo("#playerList");

    // ADD GUID TO SUBMISSION VALUES
    var playerHTML = "";
    playerHTML += "<input data-id='" + $("#playerGUID").val() + "' type='hidden' name='playerGUID[]' value='" + $("#playerGUID").val() + "' />";

    $(playerHTML).appendTo("#selected-players");

    // CLEAR INPUT FIELD
    $("#player").val('');
});

$(".control").click(function() {
    $targetID = $(this).attr('data-id');
    console.log("Selected ID:" + $targetID);

    // REMOVE WILL COME HERE
});
5
  • 1
    all the elements are removed that have the same ID?? ID have to be unique per page... Commented May 16, 2016 at 14:09
  • If you're using bad/broken code on purpose, you can't expect it to work properly. As you can see here, in case of more than one element having the same ID, jQuery will just take the first. Commented May 16, 2016 at 14:14
  • Could you please post some of your HTML code? Commented May 16, 2016 at 14:14
  • 1
    @GuruprasadRao I had the exact same reaction reading this sentence. As in "Don't tell me you did what I think you did..." Commented May 16, 2016 at 14:15
  • @GuruprasadRao ID in this case is just a HTML5 data attribute. They are fine to have the same. Commented May 16, 2016 at 14:16

3 Answers 3

2

$(".control") doesn't exist at the time you bind the click event. You will need to delegate the event like so:

$(document).on("click", ".control", function() {
    $targetID = $(this).attr('data-id');
    console.log("Selected ID:" + $targetID);
   // REMOVE WILL COME HERE
});

What happens here is that jQuery will bind a listener on the document (which always exists) rather than the .control which will not exist until you create it via a click to the #add. That way if can catch events on elements with class control even if the elements themselves were added later.

Check jQuery.on under Direct and delegated events for more details.

Note: Instead of using $(document) you can bind the event on any element which will be a parent of .control and is available when you bind the event (e.g. body). Ideally you'd want to bind it to the closest parent element which is present when the document is loaded.

Sign up to request clarification or add additional context in comments.

5 Comments

Ahh that's perfect! Thanks for the explanation. It makes perfect sense. =] will tick sooon enough! I guess I like to have all my .click() functions looking uniform so I didn't consider this.
Your description of how delegated event bindings work is correct, however, I would advise not always falling back to document as the top listener -- there is less overhead in using the first parent of the target control that will always exist, a div or something of that nature.
@Cᴏʀʏ thanks for the comment, I've added it as a note. The only reason I used the document was because I didn't know the structure of the page here.
@apokryfos: Fair enough. It looks like in this case that maybe #selected-players would work.
You're both right - I shrinked down the range of the parent and went for the closet container.
1

Try .on bind event instead of .click

$(".control").on("click",function() {
    $targetID = $(this).attr('data-id');
    console.log("Selected ID:" + $targetID);

    // REMOVE WILL COME HERE
});

Comments

1

The click() binding you're using is called a direct binding which will only attach the handler to elements that already exists. It won't get bound to elements created later. To do that, You'll have to create a "delegated" binding by using on() method.

Eg.

    <html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    </head>
    <body>

        <div id="playerList">playerList</div>

        <div id="selected-players">selected-players</div>

        <a href="#" id="add">Add</a>

    <script>

        $(document).ready(function(){

          $("#add").click(function() {

            // RENDER LIST
            var playerList = ""; //
            playerList += "<li class='selection'>Dynamic LI " + $("#player").val() + "<i class='fa fa-close control' data-id='sample-data-id " + $("#playerGUID").val() + "'> <b>iVal-Click Here</b> </i>" + "</li>";

            $(playerList).appendTo("#playerList");

            // ADD GUID TO SUBMISSION VALUES
            var playerHTML = "";
            playerHTML += "<input data-id='" + $("#playerGUID").val() + "' type='hidden' name='playerGUID[]' value='" + $("#playerGUID").val() + "' />";

            $(playerHTML).appendTo("#selected-players");

            // CLEAR INPUT FIELD
            $("#player").val('');
        });

        $("#playerList").on("click", ".control", function() {
            $targetID = $(this).attr('data-id');
            console.log("Selected ID:" + $targetID);

            // REMOVE WILL COME HERE
        });

        });

    </script>   

    </body>
    </html> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.