Check if checkbox is selected in input

Asked

Viewed 1,404 times

1

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

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

Note: I don’t want to make a script.

  • How do you want to fire an event without using a script? There is only event on the scripted page.

  • I want to call a javascript function if the box is selected, but I want to do it in input (as I explained there), I don’t want to do $('.namebox'). is(":checked")... in a part function. Understood?

  • Would not solve <input onchange="if (this.checked) call() " ... ?

  • The problem is that the box is already selected...

2 answers

2

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

I added the same function, only on onload 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>

  • The problem is that the box is already selected...

  • if it is already selected, you can call the function in the onload of your body, since the function will be fired anyway when starting the page, right? Ai you keep the onchage which will check if the user changes.

  • I edited the answer, take a look at the example.

  • 1

    @Jorgematheus only changes the alert() by a console.log(), is less intrusive for those who will check the response or see the result and has the same effectiveness.

1

From what I understand you want to call a direct Javascript event on input when loading the page in case the checkbox is marked.

Some events can be triggered on page loading without using a normal script (between tags <script></script> or a .js external). Only it is not the case of a input. An element of the 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 in this direct way on input is not possible because it does not support any event type that detects page loading.

The only way would be an event onload in the body or even 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 />

Imagery

<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 />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.