1

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

0

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>
0

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 require method 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

enter image description here

And Last Output both button

Button 1:-

enter image description here

Button 2:-

enter image description here

Hope this help you

Thanks ...

0

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>
-1

check this

<button onclick="myFunction()">Try it</button>

JS

<script>
    function myFunction() {
      alert("I am an alert box!");
      console.log('here');
    }
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.