-1

I cant get eventListener from a jsp page, i need a simple alert when click a button.

jsp code - this only draw a simple 3 buttons:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Click!</title>
</head>


<body>
    <div class="text-center p-5">
        <button class="btn btn-primary m-3" id="myBtn1">BTN1</button>
        <button class="btn btn-primary m-3" id="myBtn2">BTN2</button>
        <button class="btn btn-primary m-3" id="myBtn3">BTN3</button>
    </div>


<!-- JS -->
<script src="assets/js/sc.js"></script>
<!-- JS Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html> 

In js code put:

let id1 = document.getElementById("myBtn1");
id1.addEventListener("click", window.alert('BTN1'));

when open the navigator:

enter image description here

Show the alert - but i dont push the button !

When page is load show the buttons:

enter image description here

when press BTN1 dont show alert.

My folder extructure :

Directory extructure

The project is very simple i need to use correctly JavaScript on Spring Boot project.

Thanks for you helping !

Pl4g
  • 29
  • 4

1 Answers1

1

When you use the code id1.addEventListener("click", window.alert('BTN1')); you are using the () for the function which results in the calling of the function when the event listener is added.
To Prevent It, modify your js script as follows:

function idlistn(){window.alert('BTN1')}

let id1 = document.getElementById("myBtn1");
id1.addEventListener("click", idlistn);
mrtechtroid
  • 658
  • 3
  • 14