JavaScript to display an alert when a button is clicked using a function and an event listener
display showalert by adding two no in two input box through eventlistener using funtion in javasript
HTML:
<button id="myButton">Click me</button>
// Get a reference to the button element
var button = document.getElementById("myButton");
// Add an event listener to the button
button.addEventListener("click", showAlert);
// Define the function that will display the alert
function showAlert() {
alert("Hello, world!");
}
In this example, we first get a reference to the button element using its ID ("myButton"). We then add an event listener to the button using the addEventListener method. This method takes two arguments: the event we want to listen for (in this case, "click"), and the function that should be called when the event is triggered (in this case, showAlert).
Finally, we define the showAlert function, which simply displays an alert with the message "Hello, world!". When the button is clicked, the showAlert function will be called, and the alert will be displayed.
how to display showalert by adding two no in two input box through eventlistener using funtion in javasript
Sure! Here's an example of how to use JavaScript to display an alert with the sum of two numbers entered in two input boxes, when a button is clicked using a function and an event listener:
HTML:
<input type="text" id="num1">
<input type="text" id="num2">
<button id="myButton">Add numbers</button>
JavaScript:
// Get references to the input elements and the button element
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var button = document.getElementById("myButton");
// Add an event listener to the button
button.addEventListener("click", addNumbers);
// Define the function that will add the numbers and display the result
function addNumbers() {
// Get the values entered in the input boxes and convert them to numbers
var value1 = parseFloat(num1.value);
var value2 = parseFloat(num2.value);
// Calculate the sum of the two numbers
var sum = value1 + value2;
// Display an alert with the sum of the two numbers
alert("The sum of " + value1 + " and " + value2 + " is " + sum);
}
In this example, we first get references to the input elements and the button element using their IDs ("num1", "num2", and "myButton"). We then add an event listener to the button using the addEventListener method, which calls the addNumbers function when the button is clicked.
The addNumbers function first gets the values entered in the input boxes (num1.value and num2.value) and converts them to numbers using the parseFloat method. It then calculates the sum of the two numbers (value1 + value2) and stores the result in a variable called sum.
in html
in javasript
output
Oldest comments (0)