Problem with click event

0

I need to get the click event of a button from class btn-remove , however, it is giving the following error:

  

Uncaught ReferenceError: $ is not defined

<html> <head> <meta charset="utf-8">  </head>    
    <body>

    <h1>Teste de button</h1>

        <button class="btn-remove" data-id='2'>Deletar</button>

        <script>
            $('.btn-remove').click(function(){

             let id = $(this).attr('data-id');


            });
        </script>
    </body>
</html>
    
asked by anonymous 23.09.2018 / 19:15

1 answer

4

Possible cause of errors:

  • Library missing

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  • Codeinthewrongposition.(inyourcaseitiscorrect,underthebutton)

Seeyourcodeworking:

 $('.btn-remove').click(function(){

      let id = $(this).attr('data-id');

      console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><head><metacharset="utf-8">  </head>    
    <body>

    <h1>Teste de button</h1>

        <button class="btn-remove" data-id='2'>Deletar</button>

    </body>
</html>

The correct order is:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><head><metacharset="utf-8">  </head>    
    <body>

    <h1>Teste de button</h1>

        <button class="btn-remove" data-id='2'>Deletar</button>

    </body>
</html>


<script language="javascript">

     $('.btn-remove').click(function(){

          let id = $(this).attr('data-id');

    });

</script>

or $ (document) .ready ()

  

Code included within $( document ).ready() will only run once the Document Object Model (DOM) page is ready to run the JavaScript code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptlanguage="javascript">
     $(document).ready(function() { 
         $('.btn-remove').click(function(){

              let id = $(this).attr('data-id');

        });
     });

</script>

<html> <head> <meta charset="utf-8">  </head>    
    <body>

    <h1>Teste de button</h1>

        <button class="btn-remove" data-id='2'>Deletar</button>

    </body>
</html>
    
23.09.2018 / 20:21