Check if checkbox is selected in the input

1

I would like to trigger a direct javascript event in the input of type checkbox when it is selected. For example:

<input type="checkbox" isSelected="call()">

Note: I do not want to make a script.

    
asked by anonymous 21.02.2018 / 21:24

2 answers

3

You can use onchange and make a if that if the field is "checked", it will fire the function.

I added the same function, only in onload of the page, to call the function when the document is loaded.

function check() {     
     console.log('oi');
}
<body onload=" if(ipt1.checked) check()">
<input id="ipt1" type="checkbox" checked onload="check()" onchange="if(this.checked) check()">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</body>
    
21.02.2018 / 21:39
1

So I understand you want to call a JavaScript event direct on input on page load if checkbox is checked.

Some events can be triggered when loading the page without the use of a normal script (between the <script></script> or a .js external tags). But that is not the case with input . An element of type input only supports some events with user interaction (eg, onclick , onchange , onmouseover etc).

In view of this limitation, your intention to call an event directly in input is not possible because it does not support any type of event that detects page load.

The only way would be an event onload in body or even in any image, which supports onload :

Body

function call(){
   console.log("Checado!");
}
<body onload="if(document.body.querySelector('input[name=box]').checked) call();">
<input name="box" type="checkbox" checked />

Image

<script>
function call(){
   console.log("Checado!");
}
</script>
<img height="50" src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg"onload="if(document.body.querySelector('input[name=box]').checked) call();" />
<input name="box" type="checkbox" checked />
    
22.02.2018 / 00:41