Problem with button click event

Asked

Viewed 34 times

-1

I need to pick up the event by clicking a class button btn-remove, however, 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>
  • Do you have jQuery code being imported into your HTML? This is a classic file error that is not being imported.

  • I have no friend, only the <script></script>

  • if the answer is correct mark as accepted, see https://i.stack.Imgur.com/evLUR.png

1 answer

4


Possible causes of errors:

  • Library is missing

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
  • Code in the wrong position. (in your case it is correct, under the button)

See your code working:

 $('.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> <meta charset="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> <meta charset="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 with $( Document ).ready()

Code included within $( document ).ready() will only be executed once the Document Object Model (DOM) page is ready to execute Javascript code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script language="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>
  • Vlw friend, I will try here, God bless!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.