简体   繁体   中英

button not clicking not clicking dynamically - javascript

I am attempting to click a button dynamically using javascript to call a js function, when I launch the page, the javascript function is never called by the button to be clicked dynamically. here is my snippet

<button id="deSubmit" type="submit" >
    To be clicked automatically
</button>

<script type="text/javascript">
    document.getElementById("deSubmit").click();
</script>

Here is the js function I want to be called dynamically

$("#deSubmit").click(function () {
    $(function () {
        url_redirect({
            url: "${url}",
            method: "post"
        });
    });
........

Please what could be wrong

Call it in document.ready

 $("#deSubmit").click(function () { console.log("teste") /*$(function () { url_redirect({ url: "${url}", method: "post" }); });*/ }); $( document ).ready(function() { document.getElementById("deSubmit").click(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="deSubmit" type="submit" >To be clicked automatically</button>

Attach click event inside document.ready . Also $(function () { this wrapper is not required

 $(document).ready(function() { document.getElementById("deSubmit").click(); }) $("#deSubmit").click(function() { console.log('test') });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="deSubmit" type="submit">To be clicked automatically</button>

I don't know why you want to click a button, you can write this function on load of script as well.

You need to enclose your code inside the document ready function to make sure your document loads before any JavaScript code is executed.

And for simplicity purpose, I have invoked click event using JQuery onlu.

 $(document).ready(function() { $("#deSubmit").click(function() { /* url_redirect({ url: "${url}", method: "post" }); */ alert('function called'); }); $('#deSubmit').click(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <button id="deSubmit" type="submit"> To be clicked automatically </button>

Don't complicate with jQuery and Javascript.

  <script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {

        const btn = document.getElementById("deSubmit");

        btn.addEventListener("click", function() {
          alert("here2")
        });

        btn.click();
    });
  </script>

Use above code this will work.. just put your code in place of the alert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM