-1

Why does my this.id return undefined rather than the button's Id when clicked? I know there are slightly similar questions to this but none of the suggestions seems to work for me. Before anyone suggests, I have also tried $(this).attr("id");

Here's the code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Meh</title>
    </head>
    <body>
      <h2>Hello</h2>
      <button id="warning" class="btn">Button</button>
      <p>Button id: <span id="show"></span></p>
      <script
        src="https://code.jquery.com/jquery-3.1.1.js">
      </script>
      <script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
      </script>
      <script type="text/javascript">
        $(".btn").on("click", () => $("#show").html($(this).id));
      </script>
    </body>
</html>

Thanks!

Gonzalo.-
  • 11,500
  • 5
  • 44
  • 74
Collins Orlando
  • 1,011
  • 4
  • 11
  • 20

1 Answers1

1

Here is another way that you can do this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Meh</title>
    </head>
    <body>
      <h2>Hello</h2>
      <button id="warning" class="btn">Button</button>
      <p>Button id: <span id="show"></span></p>
      <script
        src="https://code.jquery.com/jquery-3.1.1.js">
      </script>
      <script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
      </script>
      <script type="text/javascript">
        $('.btn').click(function(event){
            $("#show").html(event.target.id);
        });
      </script>
    </body>
</html>
Moose
  • 1,134
  • 2
  • 13
  • 32