0

I am new to web development and I am trying to get my button to work. Here is my index.html:

<!-- meta tags -->
<meta charset="utf-8"
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- bootstrap css and jQuery cdn -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"</script>

<script>
    $("#btn-login").on("click", function(e) {
        e.preventDefault();
        alert("works");
    });
</script>

</head>

<body>
    <button id="btn-login" class="btn btn-primary" type="button">Login</button>
</body>

I can't seem to narrow down the issue and I've tried everything. I am just trying to get the button to trigger an alert when it is clicked. I have looked at plenty of tutorials and a bunch of other forums, but none of their fixes worked. I've tried to change the double quotes to single quotes. I've tried to remove the # before btn-login. Can anyone help me out? I'm sure it is a simple fix I am overlooking.

If it helps, I am using jQuery through Microsoft's CDN and Bootstrap3 as a stylesheet. I am also running socket.io.

Luan Tran
  • 13
  • 2

2 Answers2

0

You are not closing a tag, and you are not waiting for document ready. Try this:

<!-- meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- bootstrap css and jQuery cdn -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>

<script>
   $(document).ready(function(){
     $("#btn-login").on("click", function(e) {
        e.preventDefault();
        alert("works");
    });
});

</script>

</head>

<body>
    <button id="btn-login" class="btn btn-primary" type="button">Login</button>
</body>

Try it: https://torndualpublishing--parzibyte.repl.co/

Luis Cabrera Benito
  • 1,252
  • 11
  • 17
0

the issue here is the placement of the script. So the HTML page is rendered line by line, top to bottom. So as of now, your script tag is sitting in the head section. So when the browser reaches this line and tries to bind click event to a button with id 'btn-login'. But actually the button doesn't exist at that moment because that button tag has not been read by the browser is still to be loaded.

If you place the script tag just before the body end tag (). It will work like a charm since by that time the button will be loaded and the click event handler will be attached to the button.

d_bhatnagar
  • 1,049
  • 1
  • 10
  • 17