locked
Preventing click event running more than once RRS feed

  • Question

  • User2096382003 posted

    Within a form i have 2 radiobuttons, one of which is set to the click event so that when the page initially loads the correct data is set to a dropdownlist.

    However i only want this event to fire once, as it is it always fires when the function is called and also prevents the selection of the other radiobutton.

    setTimeout(() => {
    $("input[id$='teams_all']").click();
    },
    100);
    }

    How can i set this code to only run once?

    Wednesday, February 28, 2018 10:07 PM

All replies

  • User475983607 posted

    mark-1961

    How can i set this code to only run once?

    Move the click handler logic to a function and remove the click handler  Run the function when the page loads.

    For example, convert this

        <script>
            $("input[id$='teams_all']").click(function () {
                console.log("Hello World");
            });
        </script>

    To this

        <script>
            function toRunOnLoad() {
                console.log("Hello World");
            }
    
               
            $(function () {
                toRunOnLoad();
            });
        </script>

    Or to this if your script is at the end of the HTML

        <script>
            function toRunOnLoad() {
                console.log("Hello World");
            }
            toRunOnLoad();
        </script>

    There are plenty of valid reasons to initialize DOM elements on page load.  Loading aynchronous content that takes a while is an example. If the content is not asynchronous and you're just initializing the DOM then you should initialize the content on the server rahter than the client.  IMHO, it's easier to maintain state with a known starting point which should come from the server.

    Wednesday, February 28, 2018 10:25 PM
  • User-832373396 posted

    Hi <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">mark</g>,

    it is it always fires when the function is called

    Sir, please show us the full code.

    So that we could help you better.

    With regards, Angelina Jolie

    Thursday, March 1, 2018 2:29 AM