Search code examples
javascriptjquerygrailsgsp

Onclick remove function issue in GSP


In GSP I have written code like this which will display list of files:

       <g:each in="${fileList}" var="file">
            <div>
                <a href="#" onclick="remove('${file.attachmentId}')"> 
                <span class="glyphicon glyphicon-remove"></span></a> 
                <a href="/forms/landing/attachment/${file.attachmentId}" >${file.name}</a> 
                </br>
            </div>
        </g:each>

And my javaScript code is:

function remove(attachmentId) {
$(document).ready(function(){
        $('.glyphicon-remove').click ( function(e){
            e.preventDefault();
            $(this).parent().parent().remove();

            $.ajax({
                       url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
                        data: {
                                attachmentId: attachmentId
                        },
                        success: function(data){
                                alert("Success");
                        }

                   });

             });
        });

    }

I am calling onclick remove() function passing the selected attachmentId as the parameter. For the first time only after double click its deleting the file.

Why only after double click its deleting the file for the first time?

Thanks for your help in advance.

Note: Application is running in IE.


Solution

  • Since this tag

    <div id="remove">
    

    is present inside the g:each tag, you are creating multiple ids in the same page. When the function remove() is being called, it is removing all the divs where it finds "remove" as an id. Make each id unique and that would solve the problem

    Since you are using jQuery, try using this code. This will eliminate the use of unique id.

    <script>
            $(document).ready(function(){
                $('.glyphicon-remove').click ( function(e){
                    e.preventDefault();
                    $(this).parent().parent().remove();
                });
            });
        </script>