3

How can I trigger a button in HTML using the javascript?

I tried to use the <script></script> the HTML file and it works perfectly fine, but then I want to use a javascript file to trigger when clicking a button in HTML.

here is the code: JAVASCRIPT in HTML <head></head> tag:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js">
<script src="jsFiles/index.js"></script>

HTML:

             <div class="dropdown-menu">
              <a class="dropdown-item" href="#">Message</a>
              <a class="dropdown-item" href="#">Settings</a>
              <a class="dropdown-item" id="a_id">Log Out</a>
              </div>

JAVASCRIPT FILE:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    $(document).ready(function(){
        $("#a_id").click(function(){

            swal({title:'Logout', 
            text:'Do you want to logout this Account?', 
            icon:'warning', 
            buttons: true, 
            dangerMode: true
            })
            .then((willOUT) => {
                if (willOUT) {
                    window.location.href = 'page-logout.php', {
                    icon: 'success',
            }
            }
            });

            });
    });
</script>
12
  • Is there any error? Commented Mar 12, 2019 at 1:38
  • 1
    You don't appear to have included jQuery, yet are using jQuery methods. Commented Mar 12, 2019 at 1:38
  • @AniketG no sir. There is no error either. nothing happens when i click the button. Commented Mar 12, 2019 at 1:39
  • 2
    @AlexAbulencia put <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> in your html right above your <script src="jsFiles/index.js"></script> and try it then. jQuery wouldn't work if you don't include it, which is what Obsidian Age is saying Commented Mar 12, 2019 at 1:40
  • 1
    @AniketG . Ok sir. I'll try it. Commented Mar 12, 2019 at 1:44

1 Answer 1

2

You should remove everything is not javascript code, so your file index.js should look as follow:

$(document).ready(function() {
  $("#a_id").click(function() {

    swal({
        title: 'Logout',
        text: 'Do you want to logout this Account?',
        icon: 'warning',
        buttons: true,
        dangerMode: true
      })
      .then((willOUT) => {
        if (willOUT) {
          window.location.href = 'page-logout.php', {
            icon: 'success',
          }
        }
      });

  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! You and @Aniket G helped me a lot. Thanks

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.