GURKE
GURKE

Reputation: 153

JS checkbox trigger/click/onclick doesn't work

I have a problem triggering a click event.

This is the code which should be called by the "click":

    $('#enable_autosave').click(function () {
        if ($(this).prop('checked')) {
            document.getElementById("autosave_information").innerHTML = "Aktiviert";
            document.getElementById("warning_information_all").style = "";
            IntervalId = setInterval(function Save_Pointer(){Save();}, 10000);
        } else {
            clearInterval(IntervalId);
            document.getElementById("autosave_information").innerHTML = "Deaktiviert";
            document.getElementById("warning_information_all").style = "visibility:hidden";
        }
    });

The HTML code:

<input type="checkbox" id="enable_autosave">Test</input>

And this is the code which should trigger the checkbox' click-event after loading the page:

$('#enable_autosave').trigger('click');

The checkbox gets checked but the click-event isn't fired. I also tried .click() or .onclick() or $('#enable_autosave').attr('checked', true)[0].onclick();

But they all show the same result, the checkbox gets checked but not click-event.

Upvotes: 0

Views: 1044

Answers (2)

KirLaide
KirLaide

Reputation: 21

This is working for me (with EventListener):

<input type="checkbox" id="enable_autosave">Test</input>    
<script>
         window.onload = function() {
            'use strict';
             var foo = function() {
                var test =  document.getElementById("enable_autosave").checked;

                if(!test){
                    console.log("no");
                }
                else{
                    console.log("yes");
                }

            }
            foo();

            document.getElementById("enable_autosave").addEventListener('input', foo);
            document.getElementById("enable_autosave").addEventListener('change', foo);

        }
    </script>

Upvotes: 1

KirLaide
KirLaide

Reputation: 21

If you want alert after checkbox, do something like this:

<input type="checkbox" id="enable_autosave" onchange = 'alert("HI")'>Test</input>

Upvotes: 0

Related Questions