I want to show alert using function in phtml file as per below but it seems like the function (myfunction) is not calling.
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
require(['jquery'], function($){
function myFunction() {
alert("I am an alert box!");
}
})
</script>
4 Answers 4
The reason why the myFunction() function is not working is because it is declared inside the require() function. Functions declared inside another function cannot be called outside of it.
To fix this, you need to declare the myFunction() function outside of the require() function. You can do this by moving the myFunction() function declaration to the top of the tag, like this:
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
var myFunction = function() {
alert("I am an alert box!");
};
require(['jquery'], function($){
});
</script>
Try this code, I have checked and it's work for me.
<button name="btnname" id="trybtn">Try it</button>
<script type="text/javascript">
require(['jquery'], function($){
$('#trybtn').click(function(){
alert("I am an alert box!");
console.log("I am an alert box!");
});
})
</script>
you want to show alert box using javascript. Try this code
html code
<button onclick="myFunction()">Button1</button>
<p id="test"></p>
Write javascript in bottom in .phtml file
<script type="text/javascript">
function myFunction() {
document.getElementById("test").innerHTML;
alert("Right Alert Box");
console.log("Right Console Alert");
}
</script>
And Second You want to write code using
requiremethod write this code
html code
<button name="my_btn" id="alert_btn">Button 2</button>
Js code
<script type="text/javascript">
require(['jquery'], function($) {
$('#alert_btn').click(function() {
alert("Right Alert Box2");
console.log("Right Console Alert2");
});
})
</script>
And we have write both code in .phtml file
And Last Output both button
Button 1:-
Button 2:-
Hope this help you
Thanks ...
check this
<button onclick="myFunction()">Try it</button>
JS
<script>
function myFunction() {
alert("I am an alert box!");
console.log('here');
}
</script>